PHP Imagick - 将裁剪的图像放在另一个上面

时间:2015-02-23 15:00:27

标签: php imagick

我刚开始使用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

我该怎么办?我尝试了两个选项:

compositeImage()

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

通过在500x500px上制作一个没有任何内容的透明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参数留空,它将是透明的,但它会创建一个浅灰色背景,因此不透明。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:4)

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

<?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将图片转换为PNG(以允许透明度),然后使用setImageBackgroundColor设置透明背景。最后,使用extentImage调整其大小。