Search code examples
batch-fileimagemagickimage-resizingmogrify

Trying to use Imagemagick's Mogrify to batch resize JPGs while retaining/cloning original directories


I'm trying to create a resized copy of a very large number of photos while retaining the directory structure that they came from. Here's what I have so far:

cd /d J:\Photos_test
for /r /d %%a in (*) do magick mogrify -path "J:\Resized_test" -resize 1920x1080^> "%%~a\*.jpg"

This takes any JPGs found in the subdirectories of J:\Photos_test and creates a resized copy in J:\Resized_test.

What I want to do is recreate the source directories while doing the resize operation. So, J:\Photos_test\2018-04-19\133_PANA\P12345.JPG would be resized and placed in J:\Resized_test\2018-04-19\133_PANA\P12345.JPG

How can I do this?


Solution

  • Ok, so I got my brother to help me out a bit. This is what he came up with:

    @echo off
    setlocal EnableDelayedExpansion
    title Batch JPEG Resizer
    
    :: SOURCE FOLDER GOES HERE (NO FINAL \)
    set "jpg_source=J:\Photos"
    
    :: DESTINATION FOLDER GOES HERE (NO FINAL \)
    set "jpg_destination=J:\Resized"
    
    :: IMAGE RESOLUTION TO CONVERT TO (UNLESS SOURCE RESOLUTION IS SMALLER)
    set "image_resolution=1920x1080"
    
    cd /d %jpg_source%
    set "relative_path=%cd:~2%"
    for /f %%l in ('Powershell $Env:relative_path.Length') do (set relative_path_len=%%l)
    for /r %%b in (*.jpg *.jpeg) do (set /a "jpg_count+=1" & echo !jpg_count!)
    pause
    
    for /r %%a in (*.jpg *.jpeg) do (
        set /a "current_jpg_number+=1"
        set "current_relative_path=%%~pa"
        set "current_relative_path=!current_relative_path:~%relative_path_len%!"
        if not exist "%jpg_destination%!current_relative_path!" mkdir "%jpg_destination%!current_relative_path!"
        if not exist "%jpg_destination%!current_relative_path!%%~na%%~xa" magick convert "%%a" -resize %image_resolution%^> "%jpg_destination%!current_relative_path!%%~na%%~xa"
        echo Image !current_jpg_number! of !jpg_count!: %%a
    )
    
    pause
    

    This seems to do the trick! He added variables to make it easy to modify in the future and also included a counter and status readout. One last thing I'd like is to have the counter simply replace and update the echoed jpg_count number instead of writing it to a new line each time.