2010-03-28 52 views
3

我只是試圖使用PHP裁剪JPEG圖像(不縮放)。這是我的功能,以及輸入。PHP中的圖像裁剪產生空白結果

function cropPicture($imageLoc, $width, $height, $x1, $y1) { 
    $newImage = imagecreatetruecolor($width, $height); 

    $source = imagecreatefromjpeg($imageLoc); 
    imagecopyresampled($newImage,$source,0,0,$x1,$y1,$width,$height,$width,$height); 
    imagejpeg($newImage,$imageLoc,90); 
} 

當我把它作爲follows-- cropPicture('image.jpg', 300, 300, 0, 0) --the功能正常完成,但我留下了一個黑色的形象,是300×300像素(換句話說,一個空白的畫布)。我是否傳遞了錯誤的觀點?

圖像存在並且是可寫的。

回答

3

作爲sobedai的答案的補充:在cropPicture()中使用的那些函數的任何都可能失敗。您必須測試每個的返回值。如果發生錯誤,它們將返回false,並且您的功能無法繼續(正確)。

function cropPicture($imageLoc, $width, $height, $x1, $y1) { 
    $newImage = imagecreatetruecolor($width, $height); 
    if (!$newImage) { 
    throw new Exception('imagecreatetruecolor failed'); 
    } 

    $source = imagecreatefromjpeg($imageLoc); 
    if (!$source) { 
    throw new Exception('imagecreatefromjpeg'); 
    } 

    $rc = imagecopyresampled($newImage,$source,0,0,$x1,$y1,$width,$height,$width,$height); 
    if (!$rc) { 
    throw new Exception('imagecopyresampled'); 
    } 

    $rc = imagejpeg($newImage,$imageLoc,90); 
    if (!$rc) { 
    throw new Exception('imagejpeg'); 
    } 
} 

編輯:您可能也有興趣http://docs.php.net/error_get_last。示例腳本中的異常消息對您沒有幫助...

+0

非常感謝。從現在開始,我將開始編碼。問題出在調用'cropPicture()'的函數中。所以爲了將來的參考,我上面的代碼實際上工作! – 2010-03-28 06:34:34

+0

但請不要拋出異常_everywhere_ ;-)你可以輕易過度使用它們。見http://stackoverflow.com/questions/77127/when-to-throw-an-exception和http://stackoverflow.com/questions/1744070/why-should-exceptions-be-used-conservatively – VolkerK 2010-03-28 11:41:52

2

幾件事情:

保存

其中之一不能正常工作的返回值imagecopyresampled和imagejpeg,檢查哪個是假的,這將縮小它。

乍一看,我會先看看讀寫權限。