6

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

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
jantimon
  • 36,840
  • 23
  • 122
  • 185
  • 1
    I suspect that the documentation may be using a rather looser definition of "background color" than you're expecting. Trim in ImageMagick itself removes the background by taking the colours of the *corner pixels* of the image and working in from there, I believe. That certainly seems to be what's happening in your case. To confirm that, try using the three-colour example from the [manual](http://www.imagemagick.org/Usage/crop/#trim) -- create an image with three solid squares of colour in a row, run your trim, and see if you're left with just the centre square. – Matt Gibson Mar 18 '12 at 22:34
  • in this example, the resulting image is square, NICE... i what to MAKE SURE it's square. is there a function that can do that.... if the image is rectangle and the "remove" or the background around generate a rectangle image, i what to FORCE it to be square.... – menardmam Jul 07 '17 at 02:57

2 Answers2

10

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

jantimon
  • 36,840
  • 23
  • 122
  • 185
-1

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

$im->setImageBackgroundColor( #D5D5D5 );
Karl Barker
  • 11,095
  • 3
  • 21
  • 26