Lossless auto crop with jpegtran

Started by StarGeek, September 22, 2023, 11:59:43 AM

Previous topic - Next topic

StarGeek

Here's something I posted elsewhere that I've used that might be useful to someone here.

Jpegtran has the ability to losslessly crop jpegs on the Minimum Coded Unit (MCU) blocks, which will be 8 or 16 pixels, depending upon the jpeg.  Some programs have the ability to do this.  From what I understand, you can do this in XNView with Ctrl+U->Transformations->Image->Auto crop.  In Irfanview with the Jpeg Lossless plugin you have to select the region you want to crop (click/drag), then the Options menu->JPG Lossless Crop...(Plugln) or Ctrl+Shift+J, though there isn't the ability to autocrop.

But it can be useful to do this on the command line.  I do this with ImageMagick and jpegtran.

First, you need to get the dimensions of the crop in this format WidthxHeight+XOffset+YOffset. You can get this with this ImageMagick command, adjusting the -fuzz option as needed
magick File.jpg -fuzz 15% -trim -format "%wx%h%O" info:

This will result in the Width and Hight of the image without the borders and the offset for the upper left corner.  You then copy this into this jpegtran command
jpegtran -copy all -optimize -crop ##x##+##+## File.jpg File_Crop.jpg

Do to the way jpegs work, the right side and bottom with be an exact cut based upon these dimensions, as they don't have to be on the MCU borders, but the top and left might have a bit of border left.

As an example, using this Wiki Commons image and adding a 66 pixel border results in


running the commands
PS C:\> magick "I:\!test\LPP_MAN_Lion's_Coach_border.jpg" -fuzz 15% -trim -format "%wx%h%O" info:
800x600+66+66
PS C:\> jpegtran -copy all -optimize -crop 800x600+66+66 "I:\!test\LPP_MAN_Lion's_Coach_border.jpg" "I:\!test\LPP_MAN_Lion's_Coach_border_crop.jpg"
PS C:\>

and the result is this.  Notice there is a 2 pixel border remaining on the left and top because 66 isn't evenly divisible by 16

"It didn't work" isn't helpful. What was the exact command used and the output.
Read FAQ #3 and use that cmd
Please use the Code button for exiftool output

Please include your OS/Exiftool version/filetype

wywh

Thanks, I got it working on a macOS Sonoma 14.6 by installing ImageMagick7 via MacPorts:

sudo port install ImageMagick7
ImageMagick seems to be its own kind of app -- I did not adjust the path and now used the full path for your test image:

/opt/local/lib/ImageMagick7/bin/magick input.jpg -fuzz 15% -trim -format "%wx%h%O" info:
800x600+66+66%

After adding -outfile to your command I got it to output a similar cropped .jpg as in your example:

jpegtran -copy all -optimize -crop 800x600+66+66 -outfile output.jpg input.jpg
I'll keep this in mind if I have to losslessly crop some .jpg with maximum precision.

- Matti