Imagick PHP image image with negative offset and preserving negative space
I am using php Imagick :: cropImage and I am having problems.
Let's say I have this image:
And I want to crop the image using this cropping 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 50px x 150px (that's not what I want):
What I want is a 200px x 200px image with an alpha to fill the rest (the validation pattern illustrates transparent pixels):
How do you fill in those empty pixels?
+3
source to share
1 answer
Use Imagick :: extentImage after cropping to enlarge the image to the expected image size. Filling "blank" pixels is easy with setting background color or fill 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);
Edit
To set transparent blank pixels set matte color in front of background color
$image->setImageMatte(true);
$image->setImageBackgroundColor('transparent');
+5
source to share