Search code examples
batch-fileimagemagickdos

Batch split JPEG using ImageMagick


I use the following command to crop and split a jpg names page000.jpg in a folder producing two files

convert page000.jpg -crop 2x1@ +repage -colorspace gray ^
        +dither -colors 4 page000_%d.jpg

The two parts will be named page000_0.jpg and page000_1.jpg

It works well, but I would like to rewrite this code to work on every JPEG in a catalog.

I wrote this batch code for DOS (.bat):

mkdir split
FOR %%f IN (*.jpg) DO xcopy %%f split\
cd split
FOR %%f IN (*.jpg) DO convert %%f -crop 2x1@ +repage -colorspace gray ^
                              +dither -colors 4 %%f_%d.jpg

However, it fails to work.


Solution

  • You need to escape the percent signs that need to be interpreted not by the batch parser but by the convert parser.

    set "parameters=-crop 2x1@ +repage -colorspace gray +dither -colors 4"
    FOR %%f IN (*.jpg) DO convert "%%f" %parameters% "%%~nf_%%d.jpg"
                                                            ^^ the escaped percent sign
    

    BUT, as the for command does not use a static list of files (the list is retrieved while the for command iterates), the files generated in the process can be also processed. To solve it you can

    1 - Use a static list changing your for command into an for /f command to first retrieve the list of files using a dir command

    for /f "delims=" %%f in ('dir /b /a-d *.jpg') do .....
    

    2 - Process the input files from original directory and place the output in the split directory. That way, as the generated files are not placed in the same folder being processed, they are not detected.

    mkdir split
    set "parameters=-crop 2x1@ +repage -colorspace gray +dither -colors 4"
    FOR %%f IN (*.jpg) DO convert "%%f" %parameters% "split\%%~nf_%%d.jpg"