如何压缩图像的宽度和高度,而不是在500 x 500中裁剪

时间:2015-08-17 09:44:17

标签: php html

我可以在使用php上传后将图像裁剪为500 x 500像素。但问题是,如果图像被压缩,图像就会被裁剪掉。我希望将整个图像压缩或调整为500 x 500,而不进行裁剪。请帮忙。我提供我的代码供参考。

function resize_image($file, $width, $height) {
    list($w, $h) = getimagesize($file);

    /* calculate new image size with ratio */
    $ratio = max($width/$w, $height/$h);
    $h = ceil($height / $ratio);
    $x = ($w - $width / $ratio) / 2;
    $w = ceil($width / $ratio);

    /* read binary data from image file */
    $imgString = file_get_contents($file);

    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $image,
        0, 0,
        $x, 0,
        $width, $height,
        $w, $h);
    $ext = pathinfo($file, PATHINFO_EXTENSION); 

    //$ext will be gif

    imagejpeg($tmp, $file, 100);
    return $file;

    /* cleanup memory */

    imagedestroy($image);
    imagedestroy($tmp);
}

1 个答案:

答案 0 :(得分:-2)

我认为,echo中的HTML img会有所帮助:

<?php
echo'<img src="url of image" width="your img width" height="your img height">'
?>