开发者

HTML5 CANVAS: How to save and reopen image from server

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.getCo开发者_StackOverflow中文版ntext("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!


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜