Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Imagick crop image with negative offset and keep negative space

I'm using php Imagick::cropImage and i'm having some trouble.

Let's say I have this image:

Test Image

And I want to crop the image with this crop area: Image Crop Area

This is the PHP code I am using:

$width = 200;
$height = 200;
$x = -100;
$y = -50;

$image = new Imagick();
$image->readImage($path_to_image);
$image->cropImage( $width, $height, $x, $y );
$image->writeImage($path_to_image);
$image->clear();
$image->destroy();

The result is a 50px x 150px image (which is not what I want):

Image Crop Result

What I want is a 200px x 200px image with alpha to fill in the rest (checker pattern illustrates transparent pixels):

Image Crop Desired Result

How do I fill those empty pixels?

like image 704
ctown4life Avatar asked Apr 24 '15 13:04

ctown4life


1 Answers

Use Imagick::extentImage after cropping to grow the image to the expected image size. Filling the "empty" pixels is easy with either setting the background color, or flood filling as needed.

$width = 100;
$height = 100;
$x = -50;
$y = -25;

$image = new Imagick();
$image->readImage('rose:');
$image->cropImage( $width, $height, $x, $y );
$image->extentImage( $width, $height, $x, $y );

crop with negative offset

Fill empty pixels with background

$image = new Imagick();
$image->readImage('rose:');
$image->setImageBackgroundColor('orange');
$image->cropImage( $width, $height, $x, $y );
$image->extentImage( $width, $height, $x, $y );

fill with background color

or ImagickDraw

$image = new Imagick();
$image->readImage('rose:');
$image->cropImage( $width, $height, $x, $y );
$image->extentImage( $width, $height, $x, $y );

$draw = new ImagickDraw();
$draw->setFillColor('lime');
$draw->color(0, 0, Imagick::PAINT_FLOODFILL);
$image->drawImage($draw);

fill with draw

Edit

For setting transparent empty pixels, set matte before background color

$image->setImageMatte(true);
$image->setImageBackgroundColor('transparent');
like image 115
emcconville Avatar answered Nov 13 '22 13:11

emcconville