2012-07-23 4 views
0

안녕하세요 저는 웹에서 찾은이 기능을 바탕으로 아이콘을 업로드 할 PHP 페이지를 수정하려고했지만 이미지를 업로드하지 못하도록 제한하려고합니다. 크기는 100x100 픽셀입니다. 그럼 난 그냥이를 사용하여 호출업로드하기 전에 이미지 크기를 확인하십시오.

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 × 100 개 픽셀 크기를 초과하는 이미지를 업로드하는 경우에도 여전히 진행한다는 것입니다 :

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

이 내가 만든 기능입니다 오류를 반환하지 않고 지금 나는 그것으로 길을 잃었습니다.

답변

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

때문에 오류가있을 수 있습니다. 그러나 파일 업로드 및 업로드 중에 발생할 수있는 오류를 처리하는 더 나은 방법을 보여줍니다.

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

은 이제 하나의 기능에 새로운 기능을 가지고 : 당신이 코드를 작업의 대부분 (알 수 있지만)을 편집 할 필요가 없도록

, 그 자체의 함수로 새로운 기능을 만들 당신은 훨씬 더 쉽게 원본 코드 (잘하면 다르게 작동하는) 코드에 통합 할 수 있습니다.

사용법 :

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

그래서 당신은, 코드를 변경 가능한 작게 상처를 유지, 외과 의사처럼 할 때마다.

관련 문제