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

* Did you read FAQ #3 and use the command listed there?
* Please use the Code button for exiftool code/output.
 
* Please include your OS, Exiftool version, and type of file you're processing (MP4, JPG, etc).