0

I am working on a project which generates an image on the HTML Canvas, and then offers to download the image as a PNG.

The program has to be clientside (javascript).

I can convert the canvas to image by using

var canvas=document.getElementById('canvas');
var img    = canvas.toDataURL("image/png;base64");

And the code that is supposed to download the picture is:

    var container = document.querySelector('#container2');
//container2 is a div in HTML
    var output = container.querySelector('output');
//output is inside container2
    window.URL = window.webkitURL || window.URL;
    var prevLink = output.querySelector('a');
    if (prevLink) {
    window.URL.revokeObjectURL(prevLink.href);
    output.innerHTML = '';}
//removes the download link if already there

            var bb = new Blob([img], {data: "image/png;base64"});
//creates new blob from the img variable
    var a = document.createElement('a');
    a.download = 'test' + '.png';
//file name
    a.href = window.URL.createObjectURL(bb);
//create URL from blob
    a.textContent = 'Click here for download';

    a.dataset.downloadurl = ["image/png;base64", a.download, a.href].join(':');
    output.appendChild(a);

This works perfectly if the blobvariable is a string of text instead of the "img" variable. Instead of an image, I get af corrupted .png file which, opened in notepad gives data:image/png;base64,iVBORw0KGgoAAAANSUhEU...(long string of base64 letters), which is the correct string, but apparantly not good for PNG images. But if I write

document.write('<img src="'+img+'"/>');

The image is opened correctly in a new tab.

How can i make the downloaded image uncorrupted?

(it seems impossible to download the data generated by Canvas2image )

Elias Pedersen
  • 173
  • 1
  • 1
  • 9

1 Answers1

0

looks like you need to convert the base64 string back to a blob. here's how: Base64 encoding and decoding in client-side Javascript

The document.write might work on some browsers, if they are able to handle base64 natively.

The other problem is that JavaScript usually works with string, but to download the file you need something like a ByteArray. Here's an implementation, I've found: https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js

That's how I got it working then:

var ab = Base64Binary.decodeArrayBuffer(img.substring(22));
var bb = new Blob([ab]);
var a = document.createElement('a');
a.download = 'test' + '.png';
a.href = window.URL.createObjectURL(bb);
a.textContent = 'Click here for download';
output.appendChild(a);
Community
  • 1
  • 1
andrjas
  • 260
  • 1
  • 5
  • I tried using .atob() to decode the string. Downloading it still gave me a corrupt file, but opening it in notepad showed a resemblance to working PNG files. I compared the original image to the decoded image's code, and it seems like som parts are missing (in Notepad++ this shows up as [NUL], [STX] [FF], etc. Any idea of what's wrong? – Elias Pedersen Apr 29 '13 at 17:24