jantimon
jantimon

Reputation: 38160

How to set the trimming color in Imagick?

I am trying to remove transparent areas of an image with php using imagick.

Image Magick provides the trim method: Imagick::trimImage

Remove edges that are the background color from the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

How do I set the color which Imagick may trim?

The following script sets the background color to grey. However trim removes the blue background color as you can see below.

$im = new Imagick( "1.png" );
// Set background color to grey
$im->setImageBackgroundColor( new ImagickPixel( "rgb(213,213,213)" ) );
$im->trimImage( 0 );
$im->writeImage('2.png');

enter image description here

Is there any way to limit the trim colors?

imagick module version => 2.1.1-rc1

Upvotes: 6

Views: 4314

Answers (2)

jantimon
jantimon

Reputation: 38160

Matt Gibsons Hint led me to the right solution: http://www.imagemagick.org/Usage/crop/#trim_color

As Matt already explained the trim method takes the corner colors to trim the image. The given solution from the documentation is a workaround: They draw a border around the image before they call the trim method.

$img = new Imagick("stripes.gif"); 
// Set the color to trim:
$img->borderImage("#FF0000", 1, 1); 
$img->trimImage(0); 
$img->setImagePage(0, 0, 0, 0);
$img->writeImage("test.jpg");'

Demo

Upvotes: 10

Karl Barker
Karl Barker

Reputation: 11361

Have you tried specifying your background color as a hex code, rather than instantiating an ImagickPixel for it?

$im->setImageBackgroundColor( #D5D5D5 );

Upvotes: -1

Related Questions