使用php Imagemagick调整图像大小

时间:2012-07-09 18:37:43

标签: php imagemagick

我试图使用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;

它甚至不显示第二组回声。现在有错误。

2 个答案:

答案 0 :(得分:2)

此代码可以使用

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

从你想要的地方获取文件等。你正在使用一个带有返回值的函数,但是从不设置一个var来返回它。您还需要保存文件才能使用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">

答案 1 :(得分:0)

通过修改,您可以使用以下内容来获取宽度和高度:

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

var_dump($width, $height);

getSize方法没有记录,其返回值不是人们所期望的,所以要小心!