HTML5 CANVAS: How to save and reopen image from server

血红的双手。 提交于 2020-01-04 06:04:46

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5571303/html5-canvas-how-to-save-and-reopen-image-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!