[javascript] How to save an HTML5 Canvas as an image on a server?

I'm working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • Create an image on an HTML5 Canvas using a generative algorithm
  • When the image is completed, allow users to save the canvas as an image file to the server
  • Allow the user to either download the image or add it to a gallery of pieces of produced using the algorithm.

However, I’m stuck on the second step. After some help from Google, I found this blog post, which seemed to be exactly what I wanted:

Which led to the JavaScript code:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var ajax = new XMLHttpRequest();

  ajax.open("POST", "testSave.php", false);
  ajax.onreadystatechange = function() {
    console.log(ajax.responseText);
  }
  ajax.setRequestHeader("Content-Type", "application/upload");
  ajax.send("imgData=" + canvasData);
}

and corresponding PHP (testSave.php):

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
  $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
  $filteredData = substr($imageData, strpos($imageData, ",") + 1);
  $unencodedData = base64_decode($filteredData);
  $fp = fopen('/path/to/file.png', 'wb');

  fwrite($fp, $unencodedData);
  fclose($fp);
}
?>

But this doesn’t seem to do anything at all.

More Googling turns up this blog post which is based off of the previous tutorial. Not very different, but perhaps worth a try:

$data = $_POST['imgData'];
$file = "/path/to/file.png";
$uri = substr($data,strpos($data, ",") + 1);

file_put_contents($file, base64_decode($uri));
echo $file;

This one creates a file (yay) but it’s corrupted and doesn’t seem to contain anything. It also appears to be empty (file size of 0).

Is there anything really obvious that I’m doing wrong? The path where I’m storing my file is writable, so that isn’t an issue, but nothing seems to be happening and I’m not really sure how to debug this.

Edit

Following Salvidor Dali’s link I changed the AJAX request to be:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var xmlHttpReq = false;

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

  ajax.open("POST", "testSave.php", false);
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax.onreadystatechange = function() {
    console.log(ajax.responseText);
  }
  ajax.send("imgData=" + canvasData);
}

And now the image file is created and isn’t empty! It seems as if the content type matters and that changing it to x-www-form-urlencoded allowed the image data to be sent.

The console returns the (rather large) string of base64 code and the datafile is ~140 kB. However, I still can’t open it and it seems to not be formatted as an image.

This question is related to javascript php ajax html5-canvas

The answer is


I've worked on something similar. Had to convert canvas Base64-encoded image to Uint8Array Blob.

function b64ToUint8Array(b64Image) {
   var img = atob(b64Image.split(',')[1]);
   var img_buffer = [];
   var i = 0;
   while (i < img.length) {
      img_buffer.push(img.charCodeAt(i));
      i++;
   }
   return new Uint8Array(img_buffer);
}

var b64Image = canvas.toDataURL('image/jpeg');
var u8Image  = b64ToUint8Array(b64Image);

var formData = new FormData();
formData.append("image", new Blob([ u8Image ], {type: "image/jpg"}));

var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload", true);
xhr.send(formData);

Send canvas image to PHP:

var photo = canvas.toDataURL('image/jpeg');                
$.ajax({
  method: 'POST',
  url: 'photo_upload.php',
  data: {
    photo: photo
  }
});

Here's PHP script:
photo_upload.php

<?php

    $data = $_POST['photo'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");

    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
    die;
?>

I just made an imageCrop and Upload feature with

https://www.npmjs.com/package/react-image-crop

to get the ImagePreview ( the cropped image rendering in a canvas)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`

My implementation for uploading to Azure Blob using SAS URL

axios.post(azure_sas_url, image_in_blob, {
   headers: {
      'x-ms-blob-type': 'BlockBlob',
      'Content-Type': 'image/jpeg'
   }
})

I played with this two weeks ago, it's very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:

1) I set up a form so I can use a POST method.

2) When the user is done drawing, he can click the "Save" button.

3) When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.

document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
document.forms["form1"].submit();

4) When the form is submited I have this small php script:

<?php 
$upload_dir = somehow_get_upload_dir();  //implement this function yourself
$img = $_POST['my_hidden'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);
?>

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

http://php.net/manual/ro/function.base64-decode.php


I think you should tranfer image in base64 to image with blob, because when you use base64 image, it take a lot of log lines or a lot of line will send to server. With blob, it only the file. You can use this code bellow:

dataURLtoBlob = (dataURL) ->
  # Decode the dataURL
  binary = atob(dataURL.split(',')[1])
  # Create 8-bit unsigned array
  array = []
  i = 0
  while i < binary.length
    array.push binary.charCodeAt(i)
    i++
  # Return our Blob object
  new Blob([ new Uint8Array(array) ], type: 'image/png')

And canvas code here:

canvas = document.getElementById('canvas')
file = dataURLtoBlob(canvas.toDataURL())

After that you can use ajax with Form:

  fd = new FormData
  # Append our Canvas image file to the form data
  fd.append 'image', file
  $.ajax
    type: 'POST'
    url: '/url-to-save'
    data: fd
    processData: false
    contentType: false

This code using CoffeeScript syntax.

if you want to use javascript, please paste the code to http://js2.coffee


In addition to Salvador Dali's answer:

on the server side don't forget that the data comes in base64 string format. It's important because in some programming languages you need to explisitely say that this string should be regarded as bytes not simple Unicode string.

Otherwise decoding won't work: the image will be saved but it will be an unreadable file.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to html5-canvas

Scaling an image to fit on canvas Tainted canvases may not be exported How to fix getImageData() error The canvas has been tainted by cross-origin data? JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images Resize image with javascript canvas (smoothly) How to show a running progress bar while page is loading HTML5 Canvas Resize (Downscale) Image High Quality? HTML5 Canvas Rotate Image Real mouse position in canvas Changing three.js background to transparent or other color