for-loopbatch-fileimagemagickdelayedvariableexpansion

how to store jpg image dimensions using for command, store the results in a var, and use the var in an imagemagick command line


I am trying to use a batch script and a for loop command to find all jpg files in the working directory and then use a second for command loop to extract the image dimensions 'wxh' value for each jpg image found and temporarily store the result in a variable fsize to be used later in the script... when running imagemagick command line.

I will then run ImageMagick to optimize all the jpg files using the following command line that requires the wxh that was stored previously in the fsize variable. Since there may be multiple jpg files to act on I need to loop the command one at a time until the last image is processed by imagemagick.

I am having trouble figuring out how to keep the loop going.

I am able to get each jpg file size wxh and store it in the fsize var but when all the images have finished running the image dimensions for the jpg files don't match the original files..... this must have an error in the script and I am struggling to find the issue.

This is where I am stuck.... does anyone see something I have missed?

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /R %%G IN (*.jpg) DO (
    SET fpath=%%~fG
    SET fname=%%~nG
FOR /F "TOKENS=3" %%I IN ('MAGICK identify "!fpath!"') DO (
    SET fsize=%%I

IF "!fname!.jpg"=="!fname:*.png=!" (
    CALL :RunMagick fpath fname fsize

GOTO END

:RunMagick
ECHO MOGRIFY -monitor -path "output/!fname!" -filter Triangle -define filter:support=2 -thumbnail !fsize! -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB -format jpg "!fname!"
    )
)
EXIT /B

    IF "%ERRORLEVEL%"=="0" GOTO :END
        ECHO.
        ECHO ERROR LINE 12: && ECHO.
        ECHO CHECK SCRIPT FOR ERRORS
        PAUSE >NUL
        EXIT

:END
ECHO.
ECHO END OF SCRIPT REACHED.
PAUSE>NUL
EXIT

Solution

  • With ImageMagick v7 you can get the dimensions of the image and apply them directly to any operation within that same command. Other than some command construction issues that others have mentioned, I'd suggest eliminating the "magick identify" part you use to get the dimensions, and instead put this right in the IM command...

    ... -thumbnail %[w]x%[h] ...
    

    That simply substitutes the image dimensions for the "%[w]x%[h]".

    Note: Those escape substitutions "%[w]" for width, height, etc. probably don't work with "mogrify". If you're only processing one image at a time at that point in your command you should be able to get exactly the same result with "magick !IMG! ..." and no "mogrify".