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.
- /* Create the object and read the image in */
- $im = new Imagick( "test.png" );
- /* The background color. This is what we trim. */
- $im->setImageBackgroundColor( new ImagickPixel( "rgb(213,213,213)" ) );
- /* Trim the image. */
- $im->trimImage( 0 );
- /* Ouput the image */
- header( "Content-Type: image/" . $im->getImageFormat() );
- echo $im;
The source image is a simple png image with black circle on gray background:
The trimmed image: