1

I have a project where I need to save the image from a user drawn canvas using php. The problem is that the file saved always has a black background when I want the default to be white or transparent.

I have tried drawing a white fill in to the canvas but sketch.js wipes this away when interactions are made in the canvas.

JS

function saveImage(){
    var xmlhttp;
    xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //do something with the response
        }
    }
    xmlhttp.open("POST","upload.php",true);
    var oldCanvas = document.getElementById('colors_sketch').toDataURL("image/png");
    var img = new Image();
    img.src = oldCanvas;
    xmlhttp.setRequestHeader("Content-type", "application/upload")
    xmlhttp.send(oldCanvas);
}

PHP

$im = imagecreatefrompng($GLOBALS["HTTP_RAW_POST_DATA"]);

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

I have modified it to this as suggested but cannot seem to save

$filePath = '($GLOBALS["HTTP_RAW_POST_DATA"])';  
$savePath = 'filename.png';  //full path to saved png, including filename and extension
$colorRgb = array('red' => 255, 'green' => 0, 'blue' => 0);  //background color

$img = @imagecreatefrompng($filePath);
$width  = imagesx($img);
$height = imagesy($img);


$backgroundImg = @imagecreatetruecolor($width, $height);
$color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'],                 $colorRgb['blue']);
imagefill($backgroundImg, 0, 0, $color);


imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);


imagepng($backgroundImg, $savePath, 0);
databot
  • 131
  • 3
  • 15
  • 2
    Have you tried saving as a gif or a png? jpegs can't handle transparency. Try `imagepng($im, 'filename.png');`. Also note that `$HTTP_RAW_POST_DATA` should be avoided, as should `$GLOBALS` - the preferred method for fetching the raw post data into a string would be `file_get_contents('php://input');` – DaveRandom Apr 22 '13 at 11:43
  • Yeah I did originally. This doesn't work. Sorry I didn't post the png version. – databot Apr 22 '13 at 11:47

1 Answers1

2

You need to add background in PHP not in Canvas.

Look at this solution. Main key is to create image with background:

$backgroundImg = @imagecreatetruecolor($width, $height);
$color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
imagefill($backgroundImg, 0, 0, $color);

And copy your image on it:

imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);
Community
  • 1
  • 1
Narek
  • 3,813
  • 4
  • 42
  • 58