上传前请检查图像尺寸


Check image dimensions before upload

嗨,我根据我在网上找到的函数创建了这个函数,并尝试为我的PHP页面修改它,以便上传他们的图标,但我想限制用户上传只能为100x100px大小的图像。我只是用这个来称呼它:

uploadImage($id,$_FILES['upload']['name'],$_FILES['upload']['tmp_name']);

这是我做的功能:

 function uploadImage($new_name,$imagename,$tmp_name){
 if($tmp_name!=null||$tmp_name!=""){
     list($width, $height, $type, $attr) = getimagesize($tmp_name);
         if($width==100&&$height==100){
          $image1 = $imagename;
          $extension = substr($image1, strrpos($image1, '.') + 1);
          $image = "$new_name.$extension";
          $folder = "Images/"; 
                  if($image) { 
                    $filename = $folder.$image; 
                    $copied =  copy($tmp_name, $filename); 
                  }
                  else echo "image not uploaded.";
          }
          else
            echo "upload only 100x100px image!"; 
    }
}

现在的问题是,即使我上传了一个超过100 x 100px尺寸的图像,它仍然不会返回任何错误,现在我已经迷失了方向

您可能需要重新考虑您的代码;有一个功能可以检查上传的图像是否有效,然后实际进行上传。或者,您可以创建一个类。

<?php
class ImageUpload
{    
    public $tmpImage;
    public $maxWidth = 100;
    public $maxHeight = 100;
    public $errors = [];
    public function __construct($image)
    {
        $this->tmpImage = $image;
    }
    public function upload()
    {
        // Check image is valid; if not throw exception
        // Check image is within desired dimensions
        list($width, $height) = getimagesize($this->tmpImage);
        if ($width > $this->maxWidth || $height > $this->maxHeight) {
            throw new Exception(sprintf('Your image exceeded the maximum dimensions (%d&times;%d)', $this->maxWidth, $this->maxHeight));
        }
        // Create filename
        // Do the upload logic, i.e. move_uploaded_file()
    }
}

然后,您可以按如下方式使用此类:

<?php
$imageUpload = new ImageUpload($_FILES['upload']['tmp_name']);
try {
    $imageUpload->upload();
} catch (Exception $e) {
    echo 'An error occurred: ' . $e->getMessage();
}

这是即兴写的,所以它们可能是错误的。但希望它能展示一种更好的方法来处理文件上传,以及上传过程中可能出现的错误。

好吧,您也可以在上传后调整图像的大小。

function createFixSizeImage( $pathToImages, $pathToFixSizeImages, $Width ) 
{
  // open the directory
  $dir = opendir( $pathToImages );
  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {

  $image_info   = getimagesize( "path/to/images/".$fname );
  $image_width  = $image_info[0];
  $image_height = $image_info[1];
  $image_type   = $image_info[2];

  switch ( $image_type )
  {
    case IMAGETYPE_JPEG:

    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpeg' ) 
    {
      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );
      // give the size,u want
      $new_width = 100;
      $new_height = 100;
      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );
      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      // save Fix Size Images into a file
      imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
    }
      break;

     case IMAGETYPE_PNG:
         // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'png' ) 
    {
      // load image and get image size
      $img = imagecreatefrompng( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      $new_width = 100;
      $new_height = 100;
      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );
      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      // save Fix Size Images into a file
      imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
    }
      break;
    case IMAGETYPE_BMP:
      echo "bmp";
      break;

    default:
      break;
  }
}
  }
  // close the directory
  closedir( $dir );
}
createFixSizeImage("path","path/to/images/to/be/saved",100);

扩展或多或少未知的代码,然后对其进行调试,就像几周前写了一些代码,但现在已经不懂了。

在您的案例中,您正在通过添加检查图像大小的功能来扩展一些现有代码(您没有发布原始代码,但您写道您是这样做的)。

这样你就不需要编辑很多(未知但有效的)代码,创建新功能作为它自己的功能:

/**
 * @param string $file
 * @param int $with
 * @param int $height
 * @return bool|null true/false if image has that exact size, null on error.
 */
function image_has_size($file, $width, $height)
{
    $result = getimagesize($file);
    if ($count($result) < 2) {
        return null;
    }
    list($file_width, $file_height) = $result;
    return ($file_width == (int) $width) 
           && ($file_height == (int) $height);
}

现在,您在一个函数中拥有了新的功能,您可以更容易地将其集成到原始代码中(希望能以其他方式工作)。

用法:

$imageHasCorrectSize = image_has_size($tmp_name, 100, 100);

所以,每当你更改代码时,都要像外科医生一样,尽可能地缩小切口。