如何在上传过程中缩放后保存新的图像尺寸?

时间:2013-10-22 23:34:13

标签: php file-upload upload image-resizing

问题已编辑

以下是一个简单的脚本,允许用户上传图片。上传完成后,图片将显示为 170px(h)x 150px(W)缩略图。

大多数图片在调整大小后显示失真,所以我想我也需要缩放它们

我一直在保存新的图片尺寸。 请参阅TODO。

<?php 

if ($_SERVER["REQUEST_METHOD"] == "POST") 
{

    $maxWidth  = 150;
    $maxHeight = 170;

    $name = $_FILES ['image'] ['name'];
    $type = $_FILES ["image"] ["type"];
    $size = $_FILES ["image"] ["size"];
    $tmp_name = $_FILES ['image'] ['tmp_name']; 
    list($originalWidth, $originalHeight) = getimagesize($tmp_name);



  if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
  {
      if ($originalWidth / $maxWidth > $originalHeight / $maxHeight) 
      {
       // width is the limiting factor
       $width = $maxWidth;
       $height = floor($width * $originalHeight / $originalWidth);
      } else { 
        // height is the limiting factor
        $height = $maxHeight;
        $width = floor($height * $originalWidth / $originalHeight);
  }


   // Resample 
   $image_p = imagecreatetruecolor($maxwidth, $maxheight);
   $image = imagecreatefromjpeg($filename);
   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxwidth, $maxheight,  
   $originalWidth, $originalHeight);

    TODO: how do I save the new dimensions to $location ?

//start upload process
$RandomNumber = uniqid();
$location = "uploads/$RandomNumber";
move_uploaded_file($tmp_name, $location);   
query("UPDATE users SET profilepic = '".$location."' WHERE id = '$id'"); 


}
?>

我的一些代码受到这个问题的启发:

Distorted image resize with PHP

2 个答案:

答案 0 :(得分:1)

至于你的问题:“我怎样才能获得用户想要上传的图片的初始尺寸?”

从手册:

列表($ width,$ height,$ type,$ attr)= getimagesize(“img / flag.jpg”);

考虑到这一点,您可以使用$ _FILES [“image”]替换上例中的文件路径以获取维度数据。

获得原始尺寸后,您可以将图像调整为更小,同时保留原始高宽比。

对于错误检查,您可能想要检查$ _FILES [“image”]中只有一个文件,或者在允许为每个图像使用相同名称的多个图像上传的情况下循环遍历数组HTML输入标签。

答案 1 :(得分:0)

我有一个自定义类可以帮助我在项目中执行此操作。随意使用我的代码: https://gist.github.com/695Multimedia/7117003