如何使用Imagick将图像缩小到设定的宽度


How to reduce size of Image using Imagick to a set width?

我有一个照片库,封面照片的图像宽度为290px,高度可以是任何值。我想要一个Pinterest类型的效果。我正试图使用PHP和Imagick来实现这一点,但似乎无法实现。有人能帮忙吗?

这是我到目前为止的功能,但只是获取小图像。我在某个地方读到,将高度设置为更高的数字会使其自动运行,但无济于事。

function thumbnailImage($imagePath,$real_target_pathThumb) {
                $imagick = new Imagick($imagePath);
                $imagick->thumbnailImage(290, 9999, true, true);
                $imagick->writeImage($real_target_pathThumb);
            };

由于thumbnailImage函数不支持一维限制,因此最好的方法是使用纵横比并手动计算缩略图高度。这很简单:

$imagick = new Imagick($imagePath);
$imagick->thumbnailImage(290, (int)(290 * $imagick->getImageHeight() / $imagick->getImageWidth()));

此外,您还可以省略(或设置为false)imagick的thumbnailImage方法中的填充参数,如

$imagick->thumbnailImage(290, 9999, true);

通过指定填充参数,您告诉函数将图像放入给定的维度,然后用颜色填充所有未使用的空间。

Whithout-fill参数这种方法应该在大多数情况下都有效,但如果有人上传的图像应该高于9999px,就会失败。