2012-08-29 70 views
7

我一直在試圖讓我的應用程序(它可以在存儲它們之前動態調整圖像大小)的透明度,我認爲我已經最終縮小了關於imagealphablendingimagesavealpha很多誤導的問題。源圖像從不加載正確的透明度!PHP GD imagecreatefromstring丟棄透明度

// With this line, the output image has no transparency (where it should be 
// transparent, colors bleed out randomly or it's completely black, depending 
// on the image) 
$img = imagecreatefromstring($fileData); 
// With this line, it works as expected. 
$img = imagecreatefrompng($fileName); 

// Blah blah blah, lots of image resize code into $img2 goes here; I finally 
// tried just outputting $img instead. 

header('Content-Type: image/png'); 
imagealphablending($img, FALSE); 
imagesavealpha($img, TRUE); 
imagepng($img); 

imagedestroy($img); 

從文件加載圖像會有一些嚴重的架構困難;此代碼正在與從iPhone應用程序中查詢的JSON API一起使用,並且在這種情況下(和更一致的)在POST數據中將映像作爲base64編碼的字符串上傳更容易。我絕對需要需要以某種方式將圖像存儲爲文件(以便PHP可以將其重新加載到內存中)?是否有可能從$fileData創建一個流,可以傳遞到imagecreatefrompng

+0

無法重現'PHP 5.3.10/GD 2.0'上的問題,工作正常。你使用什麼版本?可能來自其他東西..損壞的PNG條目?像iPhone應用程序上傳質量不好的圖像?在黑暗中拍攝 – Touki

+0

我在Debian盒子上用'GD 2.0.34'(兼容2.0.34)在'PHP 5.3.16-1〜dotdeb.0'(用Suhosin)測試了這個,當我運行'imagepng 「透明部分是黑色的。這發生在我使用'imagecreatefromstring'或'imagecreatefrompng'時。 –

+0

我在PHP 5.3.10/GD(兼容2.0.34)。 – meustrus

回答

5

布萊什,這被證明是最終由於一個完全獨立的GD調用正在驗證圖像上傳。我忘了給該代碼添加imagealphablendingimagesavealpha,並且它正在創建一個新圖像,然後傳遞給調整大小的代碼。無論如何,這可能應該改變。非常感謝goldenparrot將字符串轉換爲文件名的絕佳方法。

+0

全部感謝php-devs/\ – Prasanth

2

我是否絕對需要以某種方式將圖像存儲爲文件(以便PHP可以將其重新加載到內存中)?

Documentation說:

可以使用從PHP V5.2.0 data://協議

實施例:

// prints "I love PHP" 
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo='); 
+1

你應該可以做'$ img = imagecreatefrompng('data: // image/png; base64,'。$ base64Image);' –

2

您可以使用此代碼:

$new = imagecreatetruecolor($width, $height); 

// preserve transparency 

imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)); 

imagealphablending($new, false); 

imagesavealpha($new, true); 

imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h); 

imagepng($new); 

imagedestroy($new); 

它將使透明圖像爲您服務。祝你好運 !

+1

您是否真正閱讀過這個問題或任何答案? – meustrus

+0

這把它放在一起給我。謝謝。 –