如何使用php上传时调整图像大小

时间:2015-08-17 05:34:39

标签: php

请帮助PHP代码上传图片。图像应在上传时压缩而不会影响其分辨率。此外,图像应调整为500 x 500像素。任何帮助将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:1)

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);
    imagejpeg($tmp, $file, 100);
    return $file;
    /* cleanup memory */
    imagedestroy($image);
    imagedestroy($tmp);
}

你可以这样调用这个函数:

resize_image($_FILE["fileToUpload"]["tmp_name"], 500, 500);

查看更多信息here