2012-12-06 32 views
0

我一直在試圖弄清楚這幾天。我需要上傳一張圖片,將其裁剪成方形,重新調整爲300x300,然後調整爲150x150,上傳到我的'uploads/products/$ id /'文件夾中,然後將文件路徑推入到mysql數據庫中。php imagecreatefrom結果是黑色的

但是,我一直在輸出黑色圖像。這個腳本有什麼問題?

$ext = explode('.', $_FILES['image1']['name']); 
$extension = $ext[1]; 
$target_path = 'uploads/products/'.$id.'/'; 
$filename = 'featuredpic.'.$extension; 

$featured100_full_path = $target_path.$filename; 

if(!is_dir('../../../uploads/products/'.$id)){ 
    mkdir('../../../uploads/products/'.$id, 0777); 
} 

if(file_exists('../../../'.$featured100_full_path)) { 
    chmod('../../../'.$featured100_full_path, 0755); 
    unlink('../../../'.$featured100_full_path); 
} 

if(!move_uploaded_file($_FILES['image1']['tmp_name'], '../../../'.$featured100_full_path)){ 
    echo 'Error: Image Not Uploaded!'; 
} 

if($extension=="jpg" || $extension=="jpeg"){ 
$uploadedfile = $_FILES['image1']['tmp_name']; 
$src = imagecreatefromjpeg($uploadedfile); 
    } 
else if($extension=="png"){ 
$uploadedfile = $_FILES['image1']['tmp_name']; 
$src = imagecreatefrompng($uploadedfile); 
} else { 
$src = imagecreatefromgif($uploadedfile);} 

list($width, $height) = getimagesize($filename); 
$newwidth = 300; 
$newheight = 300; 
$featured300 = imagecreatetruecolor($newwidth, $newheight); 

$newwidth1 = 150; 
$newheight1 = 150; 
$featuredthumb = imagecreatetruecolor($newwidth1, $newheight1); 

imagecopyresampled($featured300,$src,0,0,0,0,$newwidth,$newheight,$width,$height); 
imagecopyresampled($featuredthumb,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height); 

$filename_featured300 = 'uploads/products/'.$id.'/featured300.'.$extension; 
$filename_featuredthumb = 'uploads/products/'.$id.'/featuredthumb.'.$extension; 

imagejpeg($featured300, '../../../'.$filename_featured300,100); 
imagejpeg($featuredthumb, '../../../'.$filename_featuredthumb,100); 

imagedestroy($src); 
imagedestroy($tmp); 
imagedestroy($tmp1); 

回答

0

此功能可能是你的黑色圖像的原因: http://php.net/manual/en/function.imagecreatetruecolor.php

我個人步驟通過每個改性工藝確保它的功能,做你所期望的東西,我不得不承認了很多本代碼是有風險的:

$ext = explode('.', $_FILES['image1']['name']); 
$extension = $ext[1]; 

你把太多信任的文件擴展名,這是更安全: http://php.net/manual/en/function.finfo-file.php

但是,我知道這是一個額外的PECL擴展 - 所以瞭解爲什麼您可能選擇點爆炸。如果沒有爲文件上傳,目錄結構編寫包裝程序,就很難解除代碼的包裝等。

提示:繼續將圖像移動到帶有數字擴展名的臨時目錄,以便在每個轉型鏈的階段 - 它應該很快找出你的缺陷!希望這會有所幫助,對不起,我不能更有用。