【问题标题】:Crop bug in PHP Imagick?PHP Imagick 中的裁剪错误?
【发布时间】:2010-10-16 20:45:28
【问题描述】:

我试图裁剪动画 gif,在输出中我得到了相同大小的图像,但被裁剪了。

很多空白空间都被画布填满了。

例如,我有 600x100 的动画 gif,但已请求 100x100 裁剪,在输出上我得到 600x100 的图像,其中包含裁剪图像和空白空间。

有人知道这个问题的解决方案吗?

$gif = new Imagick($s['src']);

foreach($gif as $frame){
  $frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);            
}   

$gif->writeImages($s['dest_path'] .'/'. $fullname,true);

【问题讨论】:

    标签: php imagick


    【解决方案1】:

    我遇到了和你一样的问题,我发现解决方案是使用 coalesceimages 函数。

    这是一个使用 Imagick 在 php 中裁剪和调整动画 gif 大小的工作示例:

    <?php
    // $width and $height are the "big image"'s proportions
    if($width > $height) {
        $x     = ceil(($width - $height) / 2 );
        $width = $height;
    } elseif($height > $width) {
        $y      = ceil(($height - $width) / 2);
        $height = $width;
    }
    
    $image = new Imagick(HERE_YOU_PUT_BIG_IMAGE_PATH);
    $image = $image->coalesceImages(); // the trick!
    foreach ($image as $frame) {
        $frame->cropImage($width, $height, $x, $y); // You crop the big image first
        $frame->setImagePage(0, 0, 0, 0); // Remove canvas
    }
    $image = $image->coalesceImages(); // We do coalesceimages again because now we need to resize
    foreach ($image as $frame) {
        $frame->resizeImage($newWidth, $newHeight,Imagick::FILTER_LANCZOS,1); // $newWidth and $newHeight are the proportions for the new image
    }
    $image->writeImages(CROPPED_AND_RESIZED_IMAGE_PATH_HERE, true);
    ?>
    

    上面的代码用于生成具有相同高度和高度的缩略图。 你可以随意改变它。

    注意当使用 $frame->cropImage($width, $height, $x, $y);你应该把你可能需要的值放在那里。

    IE $frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $ s['params']['y']);

    当然,如果你只是想裁剪而不是裁剪和调整大小,可以这样做:

    $image = new Imagick(HERE_YOU_PUT_BIG_IMAGE_PATH);
    $image = $image->coalesceImages(); // the trick!
    foreach ($image as $frame) {
        $frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);
        $frame->setImagePage(0, 0, 0, 0); // Remove canvas
    }
    

    希望对你有帮助!

    Ps:对不起我的英语:)

    【讨论】:

    • 是的,我也这样做了。 :) 忘记发回这里。无论如何谢谢)合并是关键
    • 只是目不转睛,这将失败,因为要么定义了 $x,要么定义了 $y,但不能同时定义两者。
    【解决方案2】:

    ImageMagick 通常有一个“页面”或工作区,类似于背景层。听起来这在裁剪图像后仍然存在(我之前用命令行工具解决了一些合成和调整大小的行为很困惑......)。

    查看cropImage 的 PHP 手册页,我看到了这条评论:

    Christian Dehning - 2010 年 4 月 9 日 10:57
    裁剪 gif 图像时(我对 jpg 和 png 图像没有任何问题),画布不会被移除。请在裁剪后的 gif 上运行以下命令,以删除空格:

    $im->setImagePage(0, 0, 0, 0);
    

    【讨论】:

    • 你是在每一帧上尝试,还是在整个图像上尝试?
    • 我的 Imagick 只在裁剪高度时降低了高度。这个技巧奏效了。在裁剪命令之前添加这一行
    猜你喜欢
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多