2

I draw something with html5-canvas. then i want to save it, and when the page is loaded again, I want to load the image I saved back to the canvas. I succeed with saving the data into a file in the server, but for some reason it's a strange file that can't open by ant software, and ofcourse not by my canvas. I save it as png base64, but i tried other things that didn't work.

javascript code:

function save(){      //saves the canvas into a string as a base64 png image.   jsvalue is sent to the server by an html form
      var b_canvas = document.getElementById("a");
      var b_context = b_canvas.getContext("2d");
      var img = b_canvas.toDataURL("image/png"); 
      document.classic_form.jsvalue.value = img;

    }

            // opens the image file and displays it on the canvas
            var canvas = document.getElementById("a");
    var context = canvas.getContext("2d");
    var img = new Image();
    img.src = "backpicture.png";
    img.onload = function() {
            context.drawImage(img, 0, 0);
    };

php code:

<?php
  $str=$_POST['jsvalue'];
  $file=fopen("backpicture.txt","w");
  if(isset($_POST['submit']))
      fwrite($file,$str);
  fclose($file) 
 ?>

it creates the file, but shows nothing on the canvas when I load the page again. I also tried to use Canvas2Image.saveAsPNG(), but it still didn't work.

can you please help? thanks!

athspk
  • 6,722
  • 7
  • 37
  • 51
Amit
  • 151
  • 2
  • 6
  • Is the image hosted on the same domain as the Canvas? If not, that will throw a SECURITY_ERR exception, because the origin-clean flag will be set to false. – Simon Sarris Apr 06 '11 at 18:42
  • Why do you have it as a text file in the php fopen? –  Apr 21 '11 at 02:53

2 Answers2

3

In order to save the file properly you need to decode the base64 data (and save as png):

file_put_contents('backpicture.png', base64_decode($str));
Variant
  • 17,279
  • 4
  • 40
  • 65
1

This:

.toDataURL("image/png"); 

Will give you something like this:

image/png;base64,iVBORw0K...[base64encoded_string]...

As @Variant said, you need to base64_decode it, but, ignoring "image/png;base64,"

This should work:

file_put_contents('backpicture.png',base64_decode(substr($str,22)));
Gerard Vuyk
  • 181
  • 1
  • 2
  • 6