odd_duck
odd_duck

Reputation: 4111

PHP Imagick - Center Cropped image on top of another

I am just starting with PHP's Imageick library.

I start by cropping a users image like so:

$img_path = 'image.jpg';
$img = new Imagick($img_path);
$img_d = $img->getImageGeometry(); 
$img_w = $img_d['width']; 
$img_h = $img_d['height'];

$crop_w = 225;
$crop_h = 430;

$crop_x = ($img_w - $crop_w) / 2;
$crop_y = ($img_h - $crop_h) / 2;
$img->cropImage($img_w, $img_h, $crop_x, $crop_y);

I now need to place the cropped image of 225 x 430 onto a new image at 500px x 500px in the center. The new image must have a transparent background. Like so (the grey border is visual only):

enter image description here

How can I do so? I have tried 2 options:

compositeImage()

$trans = '500x500_empty_transparent.png';
$holder = new Imagick($trans);
$holder->compositeImage($img, imagick::COMPOSITE_DEFAULT, 0, 0);

By making a transparent png with nothing on it at 500x500px i was hoping i could use compositeImage to put the image on top of that. It does this but doesn't keep the original size of the $holder but uses the 225x430 size

frameImage()

$frame_w = (500 - $w) / 2;
$frame_h = (500 - $h) / 2;
$img->frameimage('', $frame_w, $frame_h, 0, 0);

I create a border that makes up the remaining pixels of the image to make 500 x500px. I was hoping by leaving the first colour parameter blank it would be transparent but it creates a light grey background so isn't transparent.

How can I achieve this?

Upvotes: 2

Views: 3164

Answers (1)

cdog
cdog

Reputation: 2084

If you only want a transparent background you don't need a separate image file. Just crop the image and resize it.

<?php
header('Content-type: image/png');

$path = 'image.jpg';
$image = new Imagick($path);
$geometry = $image->getImageGeometry();

$width = $geometry['width'];
$height = $geometry['height'];

$crop_width = 225;
$crop_height = 430;
$crop_x = ($width - $crop_width) / 2;
$crop_y = ($height - $crop_height) / 2;

$size = 500;

$image->cropImage($crop_width, $crop_height, $crop_x, $crop_y);
$image->setImageFormat('png');
$image->setImageBackgroundColor(new ImagickPixel('transparent'));
$image->extentImage($size, $size, -($size - $crop_width) / 2, -($size - $crop_height) / 2);

echo $image;

Use setImageFormat to convert the image to PNG (to allow transparency), then set a transparent background with setImageBackgroundColor. Finally, use extentImage to resize it.

Upvotes: 6

Related Questions