2010-06-11 25 views
2

此功能正在創建一些隨機黑色圖像,如.. 10%的時間, 並不多,但..你知道..應該發生。在error_log中給出PHP + GD創建隨機黑色縮略圖

class ImgResizer { 
private $originalFile = ''; 
public function __construct($originalFile = '') { 
    $this -> originalFile = $originalFile; 
} 
public function resize($newWidth, $targetFile) { 
    if (empty($newWidth) || empty($targetFile)) { 
     return false; 
    } 
    $src = imagecreatefromjpeg($this -> originalFile); 
    list($width, $height) = getimagesize($this -> originalFile); 
    $newHeight = ($height/$width) * $newWidth; 

    if ($newHeight<'335') { 
     //$newHeight='335'; 
    } 
    $tmp = imagecreatetruecolor($newWidth, $newHeight); 
    #$tmp = imagecreate($newWidth, $newHeight); 
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    if (file_exists($targetFile)) { 
     unlink($targetFile); 
    } 
    imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious 
} 

}

沒有錯誤。這裏是gd_info():

Array(
[GD Version] => bundled (2.0.34 compatible) 
[FreeType Support] => 
[T1Lib Support] => 
[GIF Read Support] => 1 
[GIF Create Support] => 1 
[JPG Support] => 1 
[PNG Support] => 1 
[WBMP Support] => 1 
[XPM Support] => 1 
[XBM Support] => 1 
[JIS-mapped Japanese Font Support] =>)1 

服務器是linux。函數被這樣調用: 假設$ imagen是實際的源圖像,$ imagendestino是新縮略圖的路徑和文件名。

if (!file_exists($imagendestino)) { 
     $work = new ImgResizer($imagen); 
     $work -> resize(475, $imagendestino); 
    } 

在此先感謝!

+0

您確定您啓用了錯誤日誌記錄嗎? – 2010-06-12 11:57:30

+0

失敗的確定性?即輸出文件的輸出總是相同的嗎? – 2011-02-21 13:30:58

回答

1

很可能是您傳遞非JPEG圖像。

由於JPEG功能無法讀取不同的圖像格式,因此會產生無效的圖像。結果是空白圖像,即全零,這產生黑色圖像。通過

imagecreatetruecolor($newWidth, $newHeight); 

創建時,我碰到你的類傳遞一個PNG圖像文件,它給這些警告並創建一個黑色圖像:

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'filename' is not a valid JPEG file 
Warning: imagecopyresampled(): supplied argument is not a valid Image resource 

最有可能你已經警告無效,所以你不要不會得到這些消息。

嘗試使用

imagecreatefromstring(file_get_contents(filename)) 

代替

imagecreatefromjpeg(filename) 

這樣GD自動檢測基於對你的文件頭的文件類型。