Yahya Uddin
Yahya Uddin

Reputation: 28841

ImageMagick crop Image with a surrounding background

I am using imagemagick to crop an image (using the PHP interface, but i don't think that matters too much).

I wish to crop an image, but if the crop portion goes over the image, I want it to show a background colour.

Here is the code I have so far:

$newImg = new Imagick($imgUrl);
$newImg->cropImage($cropW, $cropH, $x, $y);
$newImg->resizeImage($resizedW, $resizedH, Imagick::FILTER_CATROM, 1);
$newImg->writeImage($output_filename);

However for some reason, imagemagick refuses to show any portion of the image that is further than boundary of the image (i.e. if x and y is larger than the original image width and height, it pushes it down into view of the image).

e.g. Cropping Image using a front end tool. As you can see the crop tool is over the image The result for the cropped image pushes the image back into view. I dont want this! I want a background

I want it so that if x and y is beyond the image portion, it shows a background color instead. Thanks!

UPDATE

Thanks to namelivia suggestion I decided to use the "extent" tool.However I am unable to set a background colour using this tool through PHP. For example, the following produces a larger image but with a black background, NOT purple.

$newImg = new Imagick($imgUrl);
$newImg->setImageBackgroundColor('#e7609a'); //Doesn't return an error  (i.e. returns true) but also does not work! 
$newImg->setImageExtent(2000, 2000);
$newImg->writeImage($output_filename);

UPDATE 2

Seems like you should use extentImage (NOT setImageExtent) if you wish to use a background color.

Upvotes: 2

Views: 1040

Answers (1)

namelivia
namelivia

Reputation: 2735

I think you should use the extent option first, using extent you can also pick a background color for the area "behind" then you can crop the extended image.

Upvotes: 2

Related Questions