如何在PHP中调整上传图像的大小

时间:2014-01-31 20:02:57

标签: php image

我目前正在使用此代码,因此用户可以将图片上传到我的网站

$allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg','.JPG','.PNG','.BIF','.GIF','.JPEG'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; //  filesize in BYTES (currently 0.5MB).
$uploadpath = "/home/path/to/file/files/avatars/$_SESSION[user]";
$posted9 = hash('md5',$_SESSION["user"]).$ext; /* not for security mind you. */
// Upload the file to your specified path.
        $f = file_put_contents(
            $upload_path . $posted9,
            file_get_contents('php://input')
            );
        if($f)
    $m="Avatar updated<br/>"; // It worked.
  else
     $m="There was an error during the file upload.  Please try again."; // It failed :(.

然而,当图像被重新调整以适应我网站上的评论时,它们会变形并失去质量。

如何使用PHP来调整图像大小以保持质量?

2 个答案:

答案 0 :(得分:1)

   public function resize($width,$height) {
    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
  $this->image = $new_image;
  } 

http://us3.php.net/imagecopyresampled

答案 1 :(得分:1)

<?php

// Url of the file
$url = "/homepages/0/d502303335/htdocs/foo.jpg";

// Set a maximum height and width, I used the ones on your picture
$width = 49;
$height = 47;


// Get new dimensions
list($width_orig, $height_orig) = getimagesize($url);

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($url);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output, You can use another url, In my case i just overwrite the picture
imagejpeg($image_p, $url);

?>
这是结果: http://www.filmgratuiti.org/varie/cenBqHxMD90Q2.jpg
比你的好多了

所以基本上,在你上传文件后,你运行我的代码,你很高兴