PHP中任意调整图像大小

Jos*_*he4 3 php

将任何尺寸的图像调整为固定尺寸或至少适合固定尺寸的最佳方法是什么?

这些图像来自不受我控制的随机 URL,我必须确保图像不会超出大约 250 像素 x 300 像素或图层的 20% x 50% 的区域。

我认为我会首先确定大小,如果它超出范围,则按一个因子调整大小,但我不确定如果图像大小可以是任何大小,如何计算出调整大小的逻辑。

编辑:我没有对图像的本地访问权限,并且图像 url 在一个变量中,并使用 img src=... 输出,我需要一种方法来指定宽度和高度标签的值。

Sve*_*hal 5

使用 ImageMagick 很容易做到。您可以通过 exec 使用转换命令行工具,也可以使用http://www.francodacosta.com/phmagick/resizing-images
如果您使用“转换”,您甚至可以告诉 ImageMagick 仅调整较大图像的大小而不转换较小图像:http://www.imagemagick.org/Usage/resize/

如果您没有本地访问权限,您将无法使用 ImageMagick:

<?php
$maxWidth  = 250;
$maxHeight = 500;

$size = getimagesize($url);
if ($size) {
    $imageWidth  = $size[0];
    $imageHeight = $size[1];
    $wRatio = $imageWidth / $maxWidth;
    $hRatio = $imageHeight / $maxHeight;
    $maxRatio = max($wRatio, $hRatio);
    if ($maxRatio > 1) {
        $outputWidth = $imageWidth / $maxRatio;
        $outputHeight = $imageHeight / $maxRatio;
    } else {
        $outputWidth = $imageWidth;
        $outputHeight = $imageHeight;
    }
}
?>
Run Code Online (Sandbox Code Playgroud)