I'm using php Imagick::cropImage and i'm having some trouble.
Let's say I have this image:
And I want to crop the image with this 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):
What I want is a 200px x 200px image with alpha to fill in the rest (checker pattern illustrates transparent pixels):
How do I fill those empty pixels?
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 );
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 );
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);
For setting transparent empty pixels, set matte before background color
$image->setImageMatte(true);
$image->setImageBackgroundColor('transparent');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With