2

I have a series of images that I am converting to thumbnails using PHP ImageMagick. The images are JPEG files of products on plain white backgrounds. The white space around the images are uneven so I want to trim away the extra background. Here is what I have tried:

$im = new Imagick($imgurl);
$im->trimImage(0);
$im->thumbnailImage(200,0);
$im->writeImage("thumb/".$imgurl);

This works as far as the thumbnailImage() is concerned creating a thumbnail that is 200 px wide, but the trimImage() does not have any effect leaving me with the same amount of surrounding whitespace as in the original image.

Can anyone suggest where I am going wrong or how else I might achieve this. I understand that imagemagick trimImage() can use fuzz, but I couldn't find a good example of how this should be used.

Here is a sample image:

enter image description here

Finglish
  • 9,692
  • 14
  • 70
  • 114

1 Answers1

6

You need to add some fuzz into your trimImage()

I did a really quick experiment, that worked:

$im->trimImage(20000);

It seems around 2,000 is enough for this image. It is relative to the Quantum Range which is 65,536 if your ImageMagick is compiled with Q16. Try running:

identify | head -1

to see your Quantum Size, like this:

Version: ImageMagick 6.8.9-8 Q16 x86_64 2014-12-04

If you want to get the Quantum Range in your PHP code, use this function, then you can express it as a percentage in case you ever use a Q8 or Q32 version of ImageMagick.

If you want to experiment at the Terminal/Command-line, the equivalent command is to set the fuzz before running trim, so the following is the equivalent of $im->trimImage(6553);

convert bike.jpg -fuzz 10% -trim out.jpg
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Thanks. I tried changing the trim image value, but obviously I didn't set it nearly high enough to work. – Finglish Dec 08 '14 at 11:24
  • I made the same mistake, but I have learned to bash these things really hard till I know what they are doing, then back off if necessary! Good luck! – Mark Setchell Dec 08 '14 at 11:25