繁体   English   中英

上传前检查图像尺寸

[英]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 100像素,它仍然可以继续运行而不会返回任何错误,现在我迷失了它。

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

<?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);

因此,每当更改代码时,都应像外科医生一样进行操作,并尽可能减少切口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM