PHP GD imagecreatefromstring discards transparency

I am trying to get transparency for working with my application (which dynamically resizes images before saving them), and I think that I finally narrowed down the problem after many wrong directions to imagealphablending and imagesavealpha . The original image never loads with proper transparency!

 // With this line, the output image has no transparency (where it should be // transparent, colors bleed out randomly or it 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); 

It would be a serious architectural difficulty to load an image from a file; this code is used with the JSON API that is requested from the iPhone application, and in this case (and more consistent) it is easier to load base64 encoded images in POST data. Do I really need to somehow save the image as a file (just so that PHP can load it into memory again)? Is it possible to create a Stream from $fileData , which can be passed to imagecreatefrompng ?

+7
source share
3 answers

Blech, this was ultimately caused by a completely separate GD call that checked the loading of images. I forgot to add imagealphablending and imagesavealpha to this code, and it created a new image, which was then passed to the resize code. Which probably should be changed anyway. Many thanks goldenparrot for a great way to convert a string to a file name.

+5
source

Do I need to somehow store the image as a file (just so that PHP can load it into memory again)?

Not.

The documentation says:

You can use the data:// protocol from php v5.2.0

Example:

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

you can use this code:

 $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); 

He will make a transparent image for you. Good luck

+2
source

All Articles