Especially product images usually “suffer” from this issue; the product itself is composited on a white background and there are large areas of white around the object.

This is a simple example to demonstrate how to easily trim the areas off the image and only display the parts where the object lies.

Imagick::trimImage takes one parameter which is “fuzz”. Quoting ImageMagick manual: “By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.”

I use fuzz 0 in this example because the background color pixels are all same color.

  1. <?php
  2.  
  3. /* Create the object and read the image in */
  4. $im = new Imagick( "test.png" );
  5.  
  6. /* The background color. This is what we trim. */
  7. $im->setImageBackgroundColor( new ImagickPixel( "rgb(213,213,213)" ) );
  8.  
  9. /* Trim the image. */
  10. $im->trimImage( 0 );
  11.  
  12. /* Ouput the image */
  13. header( "Content-Type: image/" . $im->getImageFormat() );
  14. echo $im;
  15.  
  16. ?>

The source image is a simple png image with black circle on gray background:
test image

The trimmed image:
result image