Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP GD imagecreatefromstring discards transparency

Tags:

php

php-gd

I've been trying to get transparency to work with my application (which dynamically resizes images before storing them) and I think I've finally narrowed down the problem after much misdirection about imagealphablending and imagesavealpha. The source image is never loaded with proper transparency!

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

It would be some serious architectural difficulty to load the image from a file; this code is being used with a JSON API that gets queried from an iPhone app, and it's easier in this case (and more consistent) to upload images as base64-encoded strings in the POST data. Do I absolutely need to somehow store the image as a file (just so that PHP can load it into memory again)? Is there maybe a way to create a Stream from $fileData that can be passed to imagecreatefrompng?

like image 556
meustrus Avatar asked Aug 29 '12 15:08

meustrus


1 Answers

Blech, this turned out to ultimately be due to a totally separate GD call which was validating the image uploads. I forgot to add imagealphablending and imagesavealpha to THAT code, and it was creating a new image that then got passed to the resizing code. Which should probably be changed anyway. Thanks very much to goldenparrot for the excellent method of converting a string into a filename.

like image 91
meustrus Avatar answered Nov 15 '22 13:11

meustrus