Image Magick - trim and repage - loss of quality - imagemagick

When I use this command to trim a PDF file:
convert -fuzz 1% -trim +repage multi0.pdf multi0new.pdf
The result is very disappointing and the trimmed image size becomes more than 10 times lower than the source.
Is there any way to make a clean image trimming without loss of quality?
(here it is, before and after)

You probably have to use the -density option with a higher value than the default of 72 dpi. Try 300 for a start:
convert -density 300 -fuzz 1% -trim +repage multi0.pdf multi0new.pdf
Note that higher density values will increase the output file size.

Related

Imagemagick conversion process

I was trying to resize a pdf file to 8.5x11 with ImageMagick and in doing so, I am loosing the quality of my pdf file.
I was using convert source.pdf -extent 612x792 destination.pdf command.
Can someone please help me with this one?
Imagemagick is rasterizing the PDF, then scaling it, then producing an output PDF of differing dimensions, which contains raster data only.
Scale a PDF to fit directly like this:
cpdf -scale-to-fit "612 792" in.pdf -o out.pdf
This keeps the PDF's original vector artwork and fonts intact.
Imagemagick uses Ghostscript and will rasterize your PDF. It will not maintain its vectors. If you want higher quality, use a higher -density to rasterize and then resize back to whatever you want. For example, I use a density 4x the default of 72 or 288 and then resize by 25%=1/4 to get back to the nominal size.
convert -density 288 -units pixelsperinch image.pdf -resize 25% result.pdf
You can then include your -density 72 -gravity XX -extent 612x792 before the output.
Or you can compute do -density 288 etc and then just resize to 612x792.
I've tried this and it worked.
convert -density 300 -define pdf:fit-page=Letter -gravity Center source.pdf output.pdf

convert doesn't conserve size when scaling down and up

In order to make applying blur faster I'm first scaling my image down and then scale it back up:
convert - -scale 10% -blur 0x2.5 -resize 1000% RGB:-
This works most of the time but sometimes the output resolution is slightly different from the original input. Is there a way to force the pipeline to be size-preserving?
You should be able to access the original geometry of the image via %G, so you can do:
convert input.jpg -scale 10% -blur 0x2.5 -resize '%G!' RGB:-
If you are using Windows, you probably want "%G!" in double rather than single quotes.
If you are using v7 ImageMagick, replace convert with magick.
I think you are getting errors because if you take 10% of 72 pixels (say), you will get a whole number of pixels, i.e. 7 pixels and then when you scale back up by a factor of 10 you'll get 70 rather than your initial 72.
If you are using Imagemagick 7, you can do the following:
magick input.jpg -set option:wd "%w" -set option:ht "%h" -scale "%[fx:wd/10]x%[fx:ht/10]" -blur 0x2.5 -resize "%[fx:wd]x%[fx:ht]\!" RGB:-
This stores the input width and height. Then uses the stored values to scale by 1/10 of those dimensions, then does the blur, then resizes exactly back to the origin input size. Note the ! that forces the resize to the exact dimensions.
or simpler without storing the input width and height:
magick lena.jpg -scale "%[fx:w/10]x%[fx:h/10]" -blur 0x2.5 -resize "%[fx:w]x%[fx:h]\!" lena_x.jpg

Applying watermark on an image

I'm trying to apply watermark on an image using the following imagemagick command
convert input.png watermark.png.png -gravity northwest -composite output.png
The input png file size is 16KB and the watermark file size is 900bytes, but when I executed the above command to apply a watermark, the output png size is 61KB which is almost 4X the size of the original input png file. Is there any better way of applying a watermark to an image file with much better result in terms of output filesize
Test Image: https://res.cloudinary.com/deks86ilr/image/upload/v1533015495/1_rnpbye.png
Test watermark: https://res.cloudinary.com/deks86ilr/image/upload/v1533015494/2_usmonh.png
Here are my results of processing of your images with my PNG8 output using ImageMagick 6.9.10.8 Q16 with libpng 1.6.34.
I note that your input image was type palette, which means it is 8-bits of color per pixel and not 24-bit color. So it is already a low quality image.
Input (~16 KB):
Watermark Image (white on transparency -- so it is invisible here):
Convert to 24-bit PNG:
convert input.png watermark.png -gravity northwest -compose over -composite input_with_watermark.png
I see no significant visible quality loss but the output is now increase from 16 KB to 60 KB. But you can use tools such as pngcrush to compress it further.
Convert to 8-bit PNG:
convert input.png watermark.png -gravity northwest -compose over -composite PNG8:input_with_watermark2.png
The file size is now back to about 16 KB. But as you note the quality is a little poorer. This is likely because the input image (at 8-bits and has 217 colors) was first read back to 24-bits, then watermarked, which included new shades of white and then quantized back to 8-bits, but contains only 84 colors colors.
Another way is to add +dither -colors 256 to the command (the +dither turns off dithering):
convert 1_rnpbye.png 2_usmonh.png -gravity northwest -compose over -composite +dither -colors 256 PNG8:watermark3.png
This is a bit better, since it now uses 189 colors and still has a file size of 16 KB.
One final method is to save the colors from your input to a colortable image. Then use -remap to recolor the output using that colortable:
convert 1_rnpbye.png -unique-colors colortable.gif
convert 1_rnpbye.png 2_usmonh.png -gravity northwest -compose over -composite +dither -remap colortable.gif PNG8:watermark4.png
This results in 8-bit output with 227 colors and still a file size of about 16 KB. So it has a few more colors than your input and visually looks about the same quality as your input.
If you cannot reproduce these results, then perhaps you should upgrade either or both ImageMagick and libpng.

Converting PDF files at a given density when page parameter is set - ImageMagick

If the page parameter is set, conversion of PDF files at a given density outputs blank pages.
"convert -units PixelsPerInch -density 300 $myfiles -page A4 -gravity center test.pdf"
If I omit page parameter from the command, I get appropriate output but at 72dpi default resolution.
Any idea?
A4 page size is 595 x 842. So in ImageMagick you could try
convert -units PixelsPerInch -density 300 $myfiles +repage -resize 595x842 test.pdf
That will make an A4 pixel dimension image with 300 dpi. You could also do
convert -units PixelsPerInch -density 300 $myfiles +repage -resize 595x842 -density XX test.pdf
Where XX is the dpi you want when printing the image of that size.
I added +repage to remove any input image virtual canvas, since you did not specify what format images you are using for $myfiles. Without +repage, that could have caused a large bit of white space at the top of your result.
Note it is always best and most helpful to provide your ImageMagick version and platform when asking questions about its use.
While I was trying to tweak the command I found that a set density (i.e, density 300) with a given page parameter actually sets the density of the -page A4 but not the converted object on page as the set density can't actually determine resolution of the -page A4 to which it shall be applicable. As a result, the command returns blurry or blank image on set page.
However, extent parameter is what, which actually outputs the appropriate image as it is possible to set the page resolution with this parameter at a predefined density. The following example will make it absolutely clear.
Resolution of A4 size page at 300 dpi is 2480x3508, thus correct command for a set density like 300 dpi shall be:
"convert -units PixelsPerInch -density 300 $myfiles -gravity center -extent 2480x3508 test.pdf"
Resolution of A4 size page at 72 dpi is 595x842, thus correct command for a set density like 72 dpi shall be:
"convert -units PixelsPerInch -density 72 $myfiles -gravity center -extent 595x842 test.pdf"

Recommendation for compressing JPG files with ImageMagick

I want to compress a JPG image file with ImageMagick but can't get much difference in size. By default the output size is bigger than the input. I don't know why, but after adding some +profile options and setting down the quality I can get an smaller size but still similar to original.
The input image is 255kb, the processed image is 264kb (using +profile to remove profiles and setting quality to 70%). Is there any way to compress that image to 150kb at least? Is that possible? What ImageMagick options can I use?
I use always:
quality in 85
progressive (comprobed compression)
a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.
Strip any comment or EXIF metadata
in imagemagick should be
convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg
or in the newer version:
magick source.jpg -strip -interlace Plane -gaussian-blur 0.05 -quality 85% result.jpg
Source.
From #Fordi in the comments (Don't forget to upvote him if you like this):
If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel's resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.
I'm using the Google Pagespeed Insights image optimization guidelines, and for ImageMagick they recommend the following:
-sampling-factor 4:2:0
-strip
-quality 85 [it can vary, I use range 60-80, lower number here means smaller file]
-interlace
-colorspace RGB
Command in ImageMagick:
convert image.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB image_converted.jpg
With these options I get up to 40% savings in JPEG size without much visible loss.
Just saying for those who using Imagick class in PHP:
$im -> gaussianBlurImage(0.8, 10); //blur
$im -> setImageCompressionQuality(85); //set compress quality to 85
Once I needed to resize photos from camera for developing:
Original filesize: 2800 kB
Resolution: 3264x2448
Command:
mogrify -quality "97%" -resize 2048x2048 -filter Lanczos -interlace Plane -gaussian-blur 0.05
Result filesize 753 kB
Resolution 2048x2048
and I can't see any changes in full screen with my 1920x1080 resolution monitor. 2048 resolution is the best for developing 10 cm photos at maximum quality of 360 dpi. I don't want to strip it.
edit: I noticed that I even get much better results without blurring. Without blurring filesize is 50% of original, but quality is better (when zooming).
#JavisPerez -- Is there any way to compress that image to 150kb at least? Is that
possible? What ImageMagick options can I use?
See the following links where there is an option in ImageMagick to specify the desired output file size for writing to JPG files.
http://www.imagemagick.org/Usage/formats/#jpg_write
http://www.imagemagick.org/script/command-line-options.php#define
-define jpeg:extent={size}
As of IM v6.5.8-2 you can specify a maximum output filesize for the JPEG image. The size is specified with a suffix. For example "400kb".
convert image.jpg -define jpeg:extent=150kb result.jpg
You will lose some quality by decompressing and recompressing in addition to any loss due to lowering -quality value from the input.
I would add an useful side note and a general suggestion to minimize JPG and PNG.
First of all, ImageMagick reads (or better "guess"...) the input jpeg compression level and so if you don't add -quality NN at all, the output should use the same level as input. Sometimes could be an important feature. Otherwise the default level is -quality 92 (see www.imagemagick.org)
The suggestion is about a really awesome free tool ImageOptim, also for batch process.
You can get smaller jpgs (and pngs as well, especially after the use of the free ImageAlpha [not batch process] or the free Pngyu if you need batch process).
Not only, these tools are for Mac and Win and as Command Line (I suggest installing using Brew and then searching in Brew formulas).
I added -adaptive-resize 60% to the suggested command, but with -quality 60%.
convert -strip -interlace Plane -gaussian-blur 0.05 -quality 60% -adaptive-resize 60% img_original.jpg img_resize.jpg
These were my results
img_original.jpg = 13,913KB
img_resized.jpg = 845KB
I'm not sure if that conversion destroys my image too much, but I honestly didn't think my conversion looked like crap. It was a wide angle panorama and I didn't care for meticulous obstruction.
Here's a complete solution for those using Imagick in PHP:
$im = new \Imagick($filePath);
$im->setImageCompression(\Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(85);
$im->stripImage();
$im->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
// Try between 0 or 5 radius. If you find radius of 5
// produces too blurry pictures decrease to 0 until you
// find a good balance between size and quality.
$im->gaussianBlurImage(0.05, 5);
// Include this part if you also want to specify a maximum size for the images
$size = $im->getImageGeometry();
$maxWidth = 1920;
$maxHeight = 1080;
// ----------
// | |
// ----------
if($size['width'] >= $size['height']){
if($size['width'] > $maxWidth){
$im->resizeImage($maxWidth, 0, \Imagick::FILTER_LANCZOS, 1);
}
}
// ------
// | |
// | |
// | |
// | |
// ------
else{
if($size['height'] > $maxHeight){
$im->resizeImage(0, $maxHeight, \Imagick::FILTER_LANCZOS, 1);
}
}
Did some experimenting myself here and boy does that Gaussian blur make a nice different. The final command I used was:
mogrify * -sampling-factor 4:2:0 -strip -quality 88 -interlace Plane -define jpeg:dct-method=float -colorspace RGB -gaussian-blur 0.05
Without the Gaussian blur at 0.05 it was around 261kb, with it it was around 171KB for the image I was testing on. The visual difference on a 1440p monitor with a large complex image is not noticeable until you zoom way way in.
An very old but helpful answer.
I need to say, to serious large photography, -gaussian-blur is not acceptable, rather than compress ratio.
Comparing below, %95 with -gaussian-blur 0.05 vs. %85 without blurring. Original 17.5MB (8MP with much defail), %95 without blurring 5MB, %85 without blurring 3036KB, %95 with blurring 3365KB.
Comparing between blurring and compress ratio
Maybe lower blurring like 0.02 will work better.
If the image has big dimenssions is hard to get good results without resizing, below is a 60 percent resizing which for most of the purposes doesn't destroys too much of the image.
I use this with good result for gray-scale images (I convert from PNG):
ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60% -gaussian-blur 0.05 -colorspace Gray -quality 20 {}.jpg
I use this for scanned B&W pages get them to gray-scale images (the extra arguments cleans shadows from previous pages):
ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60% -gaussian-blur 0.05 -colorspace Gray -quality 20 -density 300 -fill white -fuzz 40% +opaque "#000000" -density 300 {}.jpg
I use this for color images:
ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60% -gaussian-blur 0.05 -colorspace RGB -quality 20 {}.jpg

Resources