使用 PHP Imagemagick 调整图像大小

3

我正在尝试使用ImageMagick的函数“thumbnailImage”调整图像大小。目前,我没有对图像进行任何后续处理,只是回显新的尺寸以查看它是否起作用。到目前为止,它还没有起作用。以下是我的代码。请注意:它确实回显原始尺寸,但不是新的尺寸。

$image = $_FILES["file"]["tmp_name"];

//Get original dimensions
list($width, $height, $type, $attr) = getimagesize($image);
echo "<BR>";
echo "ORIGINAL:";
echo "<BR>";
echo "Image width $width";
echo "<BR>";
echo "Image height " .$height;



  $max_height = 200;
    $max_width = 150;

 function thumbnail($image, $max_width, $max_height) {
        $img = new Imagick($image);
        $img->thumbnailImage($max_width, $max_height, TRUE);
        return $img;
    }
thumbnail($image, $max_width, $max_height);

//get new dimensions
    list($width, $height, $type, $attr) = getimagesize($img);
    echo "<BR>";
    echo "NEW:";
    echo "<BR>";
    echo "Image width $width";
    echo "<BR>";
    echo "Image height " .$height;

它甚至没有显示第二组echo。没有错误。


删除 "return $img",因为它会停止脚本从此处继续执行。之后应该可以正常工作。 - Diego Agulló
@Diego 如果我这样做,我会得到以下错误:警告: getimagesize(ÿØÿà) [function.getimagesize]:在第47行打开流失败:没有此类文件或目录 - Jonah Katz
@DiegoAgulló 添加了一个函数,所以现在返回值不应该有影响... 但是仍然存在相同的问题... 函数后面没有任何东西出现,但也没有错误。 - Jonah Katz
http://php.net/imagick.getsize 应该可以解决问题。 - Diego Agulló
1
@DiegoAgulló 好的,添加为答案,我会接受它。 - Jonah Katz
2个回答

3
这段代码可以正常运行。
$image = $_FILES["file"]["tmp_name"];  

从任何地方获取文件,使用带有返回值的函数,但从未设置变量来接收返回值。此外,您需要保存文件才能使用getimagesize。
<?
    // $image = $_FILES["file"]["tmp_name"]; // get the file from where ever you want etc
    /*
    you are using a function with a return value but never set up a var for it to return to
    as well you need to save the file in order to use getimagesize


    */
    $image = 'test.png';;

    //Get original dimensions
    list($width, $height, $type, $attr) = getimagesize($image);
    echo "<BR>";
    echo "ORIGINAL:";
    echo "<BR>";
    echo "Image width $width";
    echo "<BR>";
    echo "Image height " .$height;



      $max_height = 200;
        $max_width = 150;

     function thumbnail($image, $max_width, $max_height) {
            $img = new Imagick($image);
            $img->thumbnailImage($max_width, $max_height, TRUE);
            return $img;
        }
     // orginal line    thumbnail($image, $max_width, $max_height);
    $img=thumbnail($image, $max_width, $max_height);
    file_put_contents('testmeResize.png',$img );

    //get new dimensions
        list($width, $height, $type, $attr) = getimagesize('testmeResize.png');
        echo "<BR>";
        echo "NEW:";
        echo "<BR>";
        echo "Image width $width";
        echo "<BR>";
        echo "Image height " .$height;
        // we set it to display the image for proof it works etc
        ?>
        <br>
        <img alt="" src="testmeResize.png">

0

通过您的修改,您可以使用以下代码获取宽度和高度:

$img = thumbnail($image, $max_width, $max_height);
$width = $img->getImageWidth();
$height = $img->getImageHeight();

var_dump($width, $height);

getSize方法没有文档说明,它的返回值可能不是你期望的,所以在使用时要小心!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接