0

I know this can be done in pure PHP but could not find the solution.

Here is what I have so far:

<?php 

// posted canvas image data (string), such as: 
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArcAAAHbCAYAAADRQ7"
$data = $_POST['data'];

// remove the "data:image/png;base64," part
$uri =  substr($data,strpos($data,",")+1);

$imgData = base64_decode($uri);

// NOT WORKING: transparent to white pixels
$im = imagecreatefromstring($imgData);
$white = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $white);
// END NOT WORKING

// put the data to a file
file_put_contents('yourimage.png', $imgData);

// force user to download the image
if(file_exists('yourimage.png')){
    // save dialog box
    header('Content-Disposition: attachment; filename="yourimage.png"');
    // output png format
    header('Content-type: image/png');
    // read from server and write to buffer
    readfile('yourimage.png');
}


?>

First I tried to find out if PHP can change the image/png-String directly and modify the transparent parts, but could not find anything. Now I try to create an image from the posted string, and fail as well...

Any help appreciated.

Avatar
  • 14,622
  • 9
  • 119
  • 198
  • Does this help you? http://stackoverflow.com/questions/6109832/php-gd-create-a-transparent-png-image – Peon Oct 25 '12 at 14:53

1 Answers1

2

You're writing out the wrong file, to begin with:

file_put_contents('yourimage.png', $imgData);

is simply going to write out the original decode image sent from the client. You're using GD to manipulate that image, meaning you have to get GD to write out the modified image, e.g.

imagepng($im, 'yourimage.png');

however, since you simply seem to be dumping that image back out to the user, you can eliminate some more code and the intermediate 'yourimage.png' file with:

header('Content-type: image/png');
imagepng($im); // no filename specified, write data out to PHP's output buffer directly.
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thanks for pointing out my mistake in writing out $imgData instead of $im. When I use the suggested imagepng($im) all transparent pixels turn black. I guess I can find out why, http://stackoverflow.com/questions/12521136/php-imagepng-generating-black-image-only-on-server – Avatar Oct 25 '12 at 15:26
  • gd won't do/preserve transparency for you unless you tell it to. – Marc B Oct 25 '12 at 15:35