2010-03-12 3 views
1

배경 :
이미지를 업로드 할 스크립트가 있습니다. 하나는 원본 이미지를 유지하고 다른 하나는 이미지의 크기를 유지합니다. 1. 이미지 크기 (폭 & 높이)가 최대 치수 내에 있으면 간단하게 "복사"를 UserPics 폴더에 사용합니다. 2. 원래 크기가 최대 크기보다 큰 경우 너비와 높이의 크기를 최대 크기 이내로 조정하려고합니다. 둘 다 폴더에 이미지를 업로드하지만 사례 2에서는 이미지의 크기가 조정되지 않습니다.PHP Image resize - 왜 이미지가 업로드되었지만 크기가 조정되지 않았습니까?

질문
스크립트에 문제가 있습니까?
설정에 문제가 있습니까?

설정
서버 : WAMP 2.0
PHP : 5.3.0
php.ini라고 : GD2 활성화, 메모리 = 128M (1000M을 시도)
시도이 imageTypes 업로드 : JPG, JPEG, GIF 및 PNG (그들 모두에 대해 동일한 결과)

내가 먼저 눈에 스크립트로 잘못 아무것도 볼 수 있지만 몇 가지 테스트 출력없이 해결하고 잘못을 지독하게 어려운

if (isset($_POST['adduserpic'])) { 
    // Check errors on file 
    if ($_FILES["file"]["error"] > 0) { 
     echo $_FILES["file"]["error"]." errors<br>"; 
    } else { 
     $image =$_FILES["file"]["name"]; 
     $uploadedfile = $_FILES["file"]["tmp_name"]; 
    //Uploaded image 
    $filename = stripslashes($_FILES['file']['name']); 

    //Read filetype 
    $i = strrpos($filename,"."); 
    if (!$i) { return ""; } 
    $l = strlen($filename) - $i; 
    $extension = substr($filename,$i+1,$l); 
    $extension = strtolower($extension); 

    //New picture name = maxid+1 (from database) 
    $query = mysql_query("SELECT MAX(PicId) AS number FROM userpictures"); 
    $row = mysql_fetch_array($query); 
    $imagenumber = $row['number']+1; 

    //New name of image (including path) 
    $image_name=$imagenumber.'.'.$extension;  
    $newname = "UserPics/".$image_name; 

    //Check width and height of uploaded image 
    list($width,$height)=getimagesize($uploadedfile); 

    //Check memory to hold this image (added only as checkup) 
    $imageInfo = getimagesize($uploadedfile); 
    $requiredMemoryMB = ($imageInfo[0] * $imageInfo[1] * ($imageInfo['bits']/8) * $imageInfo['channels'] * 2.5)/1024; 
    echo $requiredMemoryMB."<br>"; 

    //Max dimensions that can be uploaded 
    $maxwidth = 20; 
    $maxheight = 20; 

    // Check if dimensions shall be original 
    if ($width > $maxwidth || $height > $maxheight) { 
     //Make jpeg from uploaded image 
     if ($extension=="jpg" || $extension=="jpeg" || $extension=="pjpeg") { 
      $modifiedimage = imagecreatefromjpeg($uploadedfile); 
     } elseif ($extension=="png") { 
      $modifiedimage = imagecreatefrompng($uploadedfile); 
     } elseif ($extension=="gif") { 
      $modifiedimage = imagecreatefromgif($uploadedfile); 
     } 
     //Change dimensions 
     if ($width > $height) { 
      $newwidth = $maxwidth; 
      $newheight = ($height/$width)*$newwidth; 
     } else { 
      $newheight = $maxheight; 
      $newwidth = ($width/$height)*$newheight; 
     } 

     //Create new image with new dimensions 
     $newdim = imagecreatetruecolor($newwidth,$newheight); 
     imagecopyresized($newdim,$modifiedimage,0,0,0,0,$newwidth,$newheight,$width,$height); 
     imagejpeg($modifiedimage,$newname,60); 

     // Remove temp images 
     imagedestroy($modifiedimage); 
     imagedestroy($newdim); 
    } else { 
     // Just add picture to folder without resize (if org dim < max dim) 
     $newwidth = $width; 
     $newheight = $height; 
     $copied = copy($_FILES['file']['tmp_name'], $newname); 
    } 

    //Add image information to the MySQL database 
    mysql_query("SET character_set_connection=utf8", $dbh); 
    mysql_query("INSERT INTO userpictures (PicId, Picext, UserId, Width, Height, Size) VALUES('$imagenumber', '$extension', '$_SESSION[userid]', '$newwidth', '$newheight', $size)") 
+0

@ 한스 : 마크 다운 파서의 코드 블록을 표시하십시오. 텍스트를 선택한 다음 ctrl + k를 누르면 텍스트가 "코드 블록"으로 해석되는 4 개의 공백으로 텍스트가 들여 쓰여집니다. – VolkerK

답변

0

이미지 크기 조정 블록이 실제로 사용되고 있는지 확인 했습니까? 거기에 몇 가지 디버그 출력을 고려하십시오. 대부분의 경우, 일부 소수 결과를 얻을 수 있습니다 및 이미지가없는 - 나는

if ($width > $maxWidth || etc...) { 
    echo "Hey, gotta shrink that there image"; 
    ... do the resizing ... 
    $resizedImage = getimagesize($newname); 
    var_dump($resizedImage); // see if the new image actually exists/what its stats are 
    etc.... 
} else { 
    echo "Woah, that's a small picture, I'll just make a straight copy instead"; 
} 

당신은 또한 $ newheight/$ newwidth 정수로 값을 반올림 할 수 있습니다 분명히 잘못 아무것도 볼 수 없습니다 소수 픽셀. AS를

옆으로, 당신은 당신의 ID 번호 생성기 경쟁 조건이있어 :

$query = mysql_query("SELECT MAX(PicId) AS number FROM userpictures"); 
$row = mysql_fetch_array($query); 
$imagenumber = $row['number']+1; 

은 거의 같은 시간을 완료 한이 개 업로드의 경우를 생각해 보자. 둘 다 동일한 ID 번호 (예 : 25)를 얻습니다. 그런 다음 업로드하는 데 시간이 오래 걸리면 더 빨리 걸리고 더 빠른 것을 덮어 씁니다.

다음과 같은 논리를 사용하여 트랜잭션을 사용하는 데이터베이스 부분을 다시 작성 :

1. start transaction 
2. insert skeleton record into the db and get its ID 
3. do image processing, copying, saving, etc... 
4. update record with the new image's stats 
5. commit the transaction 

이 방법, 트랜잭션 것이다 "숨기기"가 아직 커밋 아니에요으로 기록, 두 가지 이상 방법이 없습니다 이미지를 처리하는 동안 (RAM, 디스크 공간, 손상된 소스 이미지 등 ...) 오류가 발생하면 트랜잭션을 롤백하고 엉망진창을 정리합니다.

+0

vardump는 새 이미지의 크기가 조정되지 않았 음을 보여줍니다. "경기 조건"에 대한 의견을 보내 주셔서 감사합니다! – Hans

0

SCRIPT 또는보고.

  1. 로 설정되어 무엇 $newnameerror_reporting(E_ALL)

  2. 페이지를 복사() 명령은 당신이 켤 때 당신이 뭔가를 얻고있다 내기

무엇을 참조하십시오 높이십시오

에서 오류보고. 파일 확장자를 확인하려면 pathinfo을 사용합니다.

+0

오류보고 = 오류 없음 577.880859375 (필수 메모리) 300-20 ($ width - $ newwidth) 263-17.533333333333 ($ height - $ newheight) UserPics/25.jpg ($ newname) – Hans

+0

이상합니다. @Hans 브라우저에'imagejpeg'을 직접 출력하면 (content-type 헤더 추가) 어떻게 될까요? 크기가 조정 된 이미지를 얻습니까? –

0

1) 사용 권한을 확인하십시오. UserPics 디렉토리가 웹 프로세스를 실행하는 사용자 (예 : 데비안 시스템의 www- 데이터)에 의해 작성 될 수 있는지 확인하십시오. 필자는 이런 종류의 시스템에 대한 Windows의 시스템 사용 권한에 익숙하지 않지만, 필자가 직접 작성한다면 확인하게됩니다.

2) 자체 관련,하지만 디스크 공간을 절약하기 위해 옵트 인 GIF를 실행하고 선택 - JPG 모든 업로드 된 이미지를 http://sourceforge.net/projects/littleutils/

확인되지 않음, 손실없이 (내 애플 잃어버린 무엇을 필요로하지 않는다)

관련 문제