For this tutorial, we’ll be writing a Windows command-line batch script to extract an alpha mask from a PNG image using ImageMagick.

If you don’t know already, PNG images don’t contain a traditional alpha mask in its own channel, instead, the transparent pixels are, in a way, part of the image itself.

Below is the source image on the left and the output Alpha Mask on the right.

Extract an Alpha Mask from a PNG image

The following section provides a rigorous way to detect ImageMagick installed on any Windows computer.

While you could specify a static location for ImageMagick, this will mean that everytime you update or reinstall ImageMagick, the script would have to be updated to point to the new location, as IM put the version number within the actual folder name.

Over time, this would get tiresome over many scripts, so I developed a way to do verbosely check for ImageMagick’s install folder, and set it as a variable.

We also have to check whether or not the user is on a 64 or 32bit system. The one and only downside to this checker is if the user has installed the 32bit version of ImageMagick on a 64bit system.

REM Rigorous check for mogrify.
REM Search for mogrify in the progfiles W6432 Tree (The x64 C:Program Files folder on a 64bit machine)

IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (GOTO X64) ELSE GOTO X86

REM Take the highway to the danger zone [we didn't detect any architecture]
GOTO ARCHERR

:X86
ECHO Windows 32bit detected
SET PF=%ProgramFiles%

GOTO CONT1

:X64
ECHO Windows 64bit detected
ECHO(
SET PF64=%ProgramFiles(x86)%
SET PF=%ProgramW6432%

GOTO CONT1

:CONT1
REM Check that mogrify exists at all.
REM NOTE the second SET and the IF statement nested in the FOR loop.
REM We're assuming that the user has installed the 32bit version of IM on their 32bit machine, and 64bit IM on their 64bit machine, duh

REM Push into the current directory and start the FOR loop
REM then check IF the name is equal to "mogrify.exe"
REM Finally if one is found, SET MOGEXIST to TRUE, grab its directory and SET it as IMDIR and GOTO CONT2, the next step, breaking out of the loop
ECHO Searching for mogrify.exe in %PF% . . .
ECHO(

PUSHD "%PF%" &&(
 FOR /R "." %%i IN (*.exe) DO (
 IF /i "%%~nxi"=="mogrify.exe" (
 SET MOGEXIST=TRUE
 SET IMDIR=%%~dpi
 GOTO:CONT2
 )
 )
)

REM Old SET
REM SET IMDIR=C:Program FilesImageMagick-6.8.7-Q16

REM Flowed from mogrify check loop, this means we didn't find her
GOTO NOMOG

:CONT2
REM Now broken out of mogrify check loop, pop back out of %PFFolder%
POPD

REM MOGEXIST will only be defined if mogrify.exe is found in a subfolder of %PFFolder% (aka %PF% aka %ProgramFiles%).
REM Otherwise, it will skip our next SETMOG function and goto NOMOG error block
If Defined MOGEXIST (GOTO SETMOG) else (
 GOTO NOMOG)

Report This Post