gpt4 book ai didi

PHP Imagick - 将裁剪图像置于另一个图像之上

转载 作者:行者123 更新时间:2023-12-02 07:33:00 27 4
gpt4 key购买 nike

我刚刚开始使用 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 的裁剪图像放置到中心 500 像素 x 500 像素的新图像上。新图像必须具有透明背景。像这样(灰色边框仅是视觉效果):

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 像素。我希望通过将第一个 color 参数留空,它会是透明的,但它会创建浅灰色背景,因此不透明。

我怎样才能实现这个目标?

最佳答案

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

<?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调整其大小。

关于PHP Imagick - 将裁剪图像置于另一个图像之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com