0

こんにちは、この関数は Web で見つけたものに基づいており、アイコンをアップロードするために 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 ピクセルのサイズを超える画像をアップロードしても、エラーが返されることなく続行され、今では迷子になっていることです。

4

3 に答える 3

3

おそらく、コードを少しリファクタリングする必要があります。アップロードされた画像が有効かどうかをチェックしてから、実際にアップロードする機能があります。または、クラスを作成することもできます。

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

これはカフから書き留めたものなので、エラーである可能性があります。しかし、うまくいけば、ファイルのアップロードと、アップロード中に発生する可能性のあるエラーを処理するためのより良い方法を示しています。

于 2012-07-23T10:55:04.720 に答える
2

アップロード後に画像のサイズを変更することもできます。

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);
于 2012-07-23T11:05:16.157 に答える
1

多かれ少なかれ未知のコードを拡張してからデバッグすることは、数週間前にコードを書いて、それを理解できなくなったようなものです。

あなたの場合、画像サイズをチェックする機能を追加することで、既存のコードを拡張しています(元のコードは投稿していませんが、そのようにしたと書いています)。

(不明だが) 動作するコードの多くを編集する必要がないように、独自の機能として新しい機能を作成します。

/**
 * @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);
}

これで、新しい機能が 1 つの関数にまとめられ、元の (できれば正常に動作している) コードに簡単に統合できるようになりました。

使用法:

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

したがって、コードを変更するときはいつでも、外科医のように行い、カットをできるだけ小さく保ちます。

于 2012-07-23T11:12:48.530 に答える