【问题标题】:PHP Imagick - Center Cropped image on top of anotherPHP Imagick - 在另一个顶部中心裁剪图像
【发布时间】:2015-02-23 15:00:27
【问题描述】:

我刚开始使用 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 像素的新图像上。新图像必须具有透明背景。像这样(灰色边框仅可见):

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

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 参数留空,它会是透明的,但它会创建浅灰色背景,因此不透明。

我怎样才能做到这一点?

【问题讨论】:

    标签: php imagick


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多