PHP Imagick - 在另一张图片上居中裁剪图片

PHP Imagick - Center Cropped image on top of another

我刚开始使用 PHP 的 Imageick 库。

我首先像这样裁剪用户图像:

$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);

我现在需要将裁剪后的 225 x 430 图像放置到中心位置为 500px x 500px 的新图像上。新图像必须具有透明背景。像这样(灰色边框只是可见的):

enter image description here

我该怎么做?我尝试了 2 个选项:

compositeImage()

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

通过制作一个 500x500 像素的透明 png,上面什么也没有,我希望我可以使用 compositeImage 将图像放在上面。它这样做但不保留 $holder 的原始大小,而是使用 225x430 大小

frameImage()

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

我创建了一个边框,它构成了图像的剩余像素,使之成为 500 x500 像素。我希望通过将第一个 colour 参数留空,它会是透明的,但它会创建浅灰色背景,因此不透明。

我怎样才能做到这一点?

如果您只想要透明背景,则不需要单独的图像文件。只需裁剪图片并调整大小即可。

<?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;

使用 setImageFormat to convert the image to PNG (to allow transparency), then set a transparent background with setImageBackgroundColor. Finally, use extentImage 调整大小。