4

Beginning with a blank canvas:

<canvas id='myCanvas' width='800' height='600'></canvas>

Then initializing that canvas:

  function init_canvas(){
    var canvas = document.getElementById('myCanvas');
    context = canvas.getContext('2d');
    context.lineCap = 'round';
    // fill it with white background
    context.save();
    context.fillStyle = '#fff';
    context.fillRect(0, 0, context.canvas.width, context.canvas.height);
    context.restore();
    return;
  }

Then do a bunch of drawing on the canvas.

Then try to save it to the server using ajax and PHP on the backend.

On the client:

var img = canvas.toDataURL('image/png');
// strip the leading garbage.
img.substr(img.indexOf(',')+1).toString();

Take the resulting string, which is base64 encoded png, directly to PHP and and base64_decode() the string... The image is always the right size, but it has none of the drawing on it - just a transparent image. This doesn't seem to be an issue with base64_decode() in PHP, it seems to be a security thing or something. It fails in both Firefox 4 and the latest Chrome.

Dumping the resulting png image to firefox with "image/png" headers yields this in the error console:

Error: Image corrupt or truncated: http://somewhere.com/showimage.php
Source file: http://somewhere.com/showimage.php

But... The image isn't corrupt or truncated that I can tell unless toDataURL() is broken everywhere because the php stuff simply base64_decode() the result of toDataURL().

Any ideas?

Thanks!

Jonas
  • 121,568
  • 97
  • 310
  • 388
Erick
  • 369
  • 3
  • 13
  • you may want to look at the source of this example. http://motyarblog.000space.com/imagetouri.php jquery is used. your problem my lie in the fact the `canvas.toDataURL` is a base64 string of the image and if it exceeds 255 characters than cannot be passed as a $_GET – Lawrence Cherone Aug 02 '11 at 22:11
  • Already thought of that and confirmed that I am doing a POST operation in my XHR. On the backend, I dump the base64 encoded image to a text file and the length is fine, it's a real b64 string, unencodes fine, just a blank image. – Erick Aug 02 '11 at 22:21
  • 2
    Have you seen [this comment](http://www.php.net/manual/en/function.base64-decode.php#104193) in the PHP docs for `base64_decode`? – robertc Aug 03 '11 at 00:08
  • robertc... wow. what a freakin' joke. the whole spaces to pluses thing was it. make that comment a response and i'll mark it as the solution. thanks all. – Erick Aug 03 '11 at 05:58

4 Answers4

7

Have you seen this comment in the PHP docs for base64_decode?

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>
robertc
  • 74,533
  • 18
  • 193
  • 177
0

This work fine without returning blank image.

saveImage.php

 <?php 
        $result = array();  
        $encodedData = explode("," , $_POST['imgData'])[1];
        $encodedData = str_replace(' ','+',$encodedData);
        $decocedData = base64_decode($encodedData); 
        //Location to where you want to save image
        $NewFileName = './photos/'.$_POST['imgName'].'.jpg';
        file_put_contents($NewFileName,$decocedData);
        $result['status'] = 1;
        $result['saveImage'] = $NewFileName;
        echo json_encode($result);
    ?>

script.js

<script>
//This post the data to server on fly

function saveImage(canvasData,FileName) {
  var xmlHttpReq = false;

  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
  }

  ajax.open("POST", "saveImage.php", false);
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {
        var rawArr = JSON.parse(this.responseText);
        var ImagePreviewer= document.getElementById("ImagePreviewer");
    ImagePreviewer.src=rawArr.saveImage;
    //console.log(rawArr.saveImage);
    }

  }
  ajax.send("imgData=" + canvasData+"&imgName=" + FileName);
}
// Call this with button click or whatever you want 
function saveJPG(filename) {
//do other logic here
var dataURL = TheCanvas.toDataURL("image/jpg");
    saveImage(dataURL,filename);
}
<script>
ShapCyber
  • 3,382
  • 2
  • 21
  • 27
0

is it like my problem before ?

may be you can check on

jQuery and Canvas.toDataURL

and

Security error" code: "1000 on Firefox with Canvas.toDataURL

Community
  • 1
  • 1
ilumin
  • 608
  • 12
  • 22
-1

In JavaScript send the result from canvas.toDataURL() on those browsers than support this method with the default type of "image/png".

var imageInfo = canvas.toDataURL();

Direct way to create the png file:

<?php
$imageInfo = imageInfoFromBrowser(); // Your method to get the data
$image = fopen($imageInfo, 'r');
file_put_contents("fileName.png", $image);
fclose($image);
?>

I have this working in PHP 5.3, for other version, please check.

Image data sample for testing on PHP.

$imageDataInfoSample = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMYAAAC0CAYAAADPcVOXAAAHx0lEQVR4Xu2dPY5dRRBGsUSI+Umdk2KQQwfMsAHERtgDrABYgCMvADJHYIeOLDZBhgjJgG6JKz2PZ+bVu7f6666qM1LLI03frqpTfd79mfF7D97jCwIQeIfAA5hAAALvEkAMdgUEbiGAGGwLCCAGewACNgKcMWycmFWMAGIUazjl2gggho0Ts4oRQIxiDadcGwHEsHFiVjECiFGs4ZRrI4AYNk7MKkYAMYo1nHJtBBDDxolZxQggRrGGU66NAGLYODGrGAHEKNZwyrURQAwbJ2YVI4AYxRpOuTYCiGHjxKxiBBCjWMMp10YAMWycmFWMAGIUazjl2gggho0Ts4oRQIxiDadcGwHEsHFiVjECiFGs4ZRrI4AYNk7MKkYAMYo1nHJtBBDDxolZxQggRrGGU66NAGLYODGrGAHEKNZwyrURQAwbJ2bdTeBZ+9HjNp5kgoQYmbo5p5YXLezDNp7OCT8mKmKM4Vpp1V9bsX0fXWcqGjEydXNOLYgxhztRFyeAGIs3yJJeyhtFS+ED5yDGQLiqpVPeKKrg3REHMSY3wCN8yiZ6gDmwRkqm1W6+UzbxwKb2ODQlU8Tw2Bq110CMBP1P2cTJfUnJlDPG5F2VIDxi0MQEBPxLQAx/pvIVUzZRTvHtgCmZcik1eVclCI8YNDEBAf8SEMOfqXzFlE2UU+RSajJy//CIAVMTAe4xTJiYdA+BlC82iMGeP0oAMY4SXOD4lE2czDUlU84Yk3dVgvCIQRMTEPAvATH8mcpXTNlEOUUe105G7h8eMWBqIsA9hgkTk3hcm3sPcMbw729Kppwx/DdKtRURI0HHUzZxcl9SMuWMMXlXJQiPGDQxAQH/EhDDn6l8xZRNlFPk9xiTkfuHRwyYmghwj2HCxCR+j5F7D3DG8O9vSqacMfw3SrUVESNBx1M2cXJfUjLljDF5VxF+TQKIsWZfy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fTYzKm5DahQQQQwibUHEIIEacXpGpkABiCGETKg4BxIjTKzIVEkAMIWxCxSGAGHF6RaZCAoghhE2oOAQQI06vyFRIADGEsAkVhwBixOkVmQoJIIYQNqHiEECMOL0iUyEBxBDCJlQcAogRp1dkKiSAGELYhIpDADHi9IpMhQQQQwibUHEIIEacXpGpkABiCGETKg4BxIjTKzIVEkAMIWxCxSGAGHF6RaZCAoghhE2oOAQQY51ePWupPG7jyTop1c0EMdbp/YuWysM2nq6TUt1MEGOd3od9y/x1EPplghh+LI+uhBhHCToejxiOMA8uhRgHAXoejhieNI+thRjH+LkejRiuOA8thhiH8PkejBi+PI+s9kc7+IM2Pmzj6zZ+ObIYxx4jgBjH+Hke/Wdb7P02PvJclLX2EUCMfdxGHPVPW/RVG9cjFmfNywggxmW8Rs3ePl+w9wMxRlG+YF3EuADW4Knbh8W/uSUOn3U+GP7N5RFDDPwk3PP2/aMb4funoN72dVMWRBncN8QYDPie5V+3n/29M/zVzuM4zEgAMYygmFaLAGLU6jfVGgkghhEU02oRQIxa/aZaIwHEMIJiWi0CiFGr31RrJIAYRlBMq0UAMWr1m2qNBP4DoE6utZfjM60AAAAASUVORK5CYII="
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Daniel De León
  • 13,196
  • 5
  • 87
  • 72