繁体   English   中英

使用PHP生成Imagemagick缩略图-使用-crop

[英]Imagemagick thumbnail generation with php - using -crop

很久以前,我创建了一个小型库,用于通过system(...)使用imagemagick来调整图像的大小,因为我认为PHP的内置imagemagick函数不够用。

但是,最近我不得不将此移植到symfony项目中,并且选择使用sfThumbnailPlugin(如果我没记错的话)。 不幸的是,这不包括裁剪功能-即指定所需的大小,例如300x300 px,并裁剪了缩略图以使其适合。 我选择自己实现此功能,但似乎出了点问题。

每当我将图像大小调整为所需大小时,如果宽度大于高度,则比例会被拧紧。 看一下这个例子: http : //i37.tinypic.com/9hkqrl.png-在这个例子中,最上面一行是正确的比例,最下面一行是问题。

在示例中,顶部和底部应已裁剪。

这是完成裁剪的部分的代码(变量名应该是不言自明的):

<?php
    if ($width/$height > $this->maxWidth/$this->maxHeight) {
      // then resize to the new height...
                $command .= ' -resize "x'.$this->maxWidth.'"';

                // ... and get the middle part of the new image
                // what is the resized width?
                $resized_w = ($this->maxWidth/$height) * $width;

                // crop
                $command .= ' -crop "'.$this->maxHeight.'x'.$this->maxWidth.'+'.round(($resized_w - $this->maxWidth)/2).'+0"';
            } else {
                // or else resize to the new width
                $command .= ' -resize "'.$this->maxHeight.'x"';

                // ... and get the middle part of the new image
                // what is the resized height?
                $resized_h = ($this->maxHeight/$width) * $height;

                // crop
                $command .= ' -crop "'.$this->maxWidth.'x'.$this->maxHeight.
                             '+0+'.round(($resized_h - $this->maxHeight)/2).'" +repage';
            }

是生成错误代码的if语句的第二部分。

谁能为我纠正这个问题? 显然,计算是错误的。

解决方案如下:

    if ($width/$height > $this->maxWidth/$this->maxHeight) {
      // then resize to the new height...
                $command .= ' -resize "x'.$this->maxHeight.'"';

                // ... and get the middle part of the new image
                // what is the resized width?
                $resized_w = ($this->maxHeight/$height) * $width;

                // crop
                $command .= ' -crop "'.$this->maxWidth.'x'.$this->maxHeight.'+'.round(($resized_w - $this->maxWidth)/2).'+0" +repage';
            } else {
              $command .= ' -resize "' . $this->maxWidth . 'x"';
              $resized_h = ($this->maxWidth/$width) * $height;

                // crop
                $command .= ' -crop "'.$this->maxWidth.'x'.$this->maxHeight.
                             '+0+'.round(($resized_h - $this->maxHeight)/2).'" +repage';
            }

我告诉你一个建议,你可以尝试一下,

我看到图片链接,我认为条件检查不正确。

您已检查条件[(宽度/高度)>(maxWidth / maxHeight)]而不是检查

if(width == height){} elseif(width> height){} else(width <height){}

检查此条件,并根据此条件裁剪图像并调整尺寸。

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM