Search code examples
batch-fileimagemagickbatch-processingphotos

Batch Script drag and drop folder convert images with ImageMagick


Firstly I've tried looking everywhere, and was unsuccessful. I am inexperienced and appreciate any help at all. I'm trying to write a script to drag a folder onto a batch file, which will then convert all images in that folder to jpgs, using ImageMagick. I can see it's very possible to execute the script on the command line, that all works fine. But to drag a folder is giving me issues. I can drag many files onto the script and it converts fine:

convert %* %1.jpg

that works great. I can also drag a folder, and it will convert the images inside, but rename then as the name of the folder, one directory higher, like so:

@set SOURCE=%1
convert %SOURCE%\* %SOURCE%.jpg

I imagine i need a for loop performing the convert on every file in the folder. But I have run into problems. I'm unsure where to put quotes, and what variables to use, and how to overcome spaces. I imagine something like this...

for %%f in (%SOURCE%\*) do ( convert %%f "%SOURCE%\%%f.jpg" )

But yeah, I'm at a loss. I'm trying this little project both to learn, and also to help my dad convert large amounts of his photos quickly.


Solution

  • It sounds like ImageMagick can take multiple input arguments and one output argument, but to simplify it with one file at a time try the following. Your loop looks right but the ~ changes below will handle quotes.

    You may also want to change the %%a* match to be particular files so you don't catch existing jpgs or non-image files, e.g. for %%f in (%%a*.png %%a*.gif) do ...

    Finally, add an "echo" in front of the two convert lines so you can do a test run.

    @echo off
    
    rem Loops through arguments. If a file converts it to a jpg.  If a directory
    rem converts files in that directory to jpgs.  Assumes a program "convert".
    
    set count=0
    for %%a in (%*) do (
      if exist %%a (
        if exist %%a\ (
          rem Directory, loop through contents
          for %%f in (%%a\*) do (
            convert "%%f" "%%~a\%%~nf.jpg"
            set /a count+=1
          )
        ) else (
          rem File, just convert
          convert "%%~a" "%%~na.jpg"
          set /a count+=1
        )    
      ) else (
        echo Skipping non-existent %%~a
      )
    )
    
    echo Converted %count% files
    
    pause