duanlu0559 2014-04-29 16:54
浏览 52
已采纳

Imagemagick - 包含裁剪中的图像

I don't use Imagemagick very often, which is why I don't know how to solve this problem. I also don't know how to phrase the question other than: How do I get the image to be cropped like the CSS property: background-size: contain; I haven't been able to find an answer, likely due to my phrasing.

I need the image to be 200px, and "resized/cropped" so that it is not stretched, but contained by the width or height (dependent on the orientation of the image width > height = contain by width)

What I have so far:

$im = new Imagick($path);

/* Resizing Operations */

$gm = $im->getImageGeometry();
$w = $gm['width'];
$h = $gm['height'];

if($h < $w) {
    $nh = 200;
    $nw = (200 / $h) * $w;
} else {
    $nw = 200;
    $nh = (200 / $w) * $h;
}

$im->resizeImage($nw, $nh, Imagick::FILTER_LANCZOS, true);
$im->cropThumbnailImage(200,200);

/* End Resizing Operations */

Which produces an image with the center chopped out.

Here's a visual example

We have this logo:

Original Logo


And then we want it to be constrained to 200px wide and 200px high, contained:

resized

Essentially like setting the canvas height, while not adjusting the image height.

  • 写回答

2条回答 默认 最新

  • douchigu1723 2014-04-29 18:25
    关注

    Came up with this algorithm based on the extent method of ImageMagick, which achieves the same result as CSS's background-size: contain;

    You can set the 200 value in the resizeImage function to get your end product. Works beautifully!

    $im = new Imagick($path);
    
    /* Resizing Operations */
    $gm = $im->getImageGeometry();
    $w = $gm['width'];
    $h = $gm['height'];
    
    if($h < $w) {
        $sr = $w;
        $horz = TRUE;
    } else if($h > $w) {
        $sr = $h;
        $horz = FALSE;
    } else {
        $square = TRUE;
    }
    
    if(!$square && $horz) {
        $srs = $sr / 2;
        $extent_amt = $srs - ($h / 2);
        $im->extentImage($sr, $sr, 0, 0 - $extent_amt);
    } else if(!$square && !$horz) {
        $srs = $sr / 2;
        $extent_amt = $srs - ($w / 2);
        $im->extentImage($sr, $sr, 0 - $extent_amt, 0);
    }
    
    $im->resizeImage(200, 200, Imagick::FILTER_LANCZOS, true);
    
    /* End Resizing Operations */
    
    $im->writeImage($path);
    
    /* Clean up time */
    $im->clear();
    $im->destroy();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)