Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  71] [ 2]  / answers: 1 / hits: 21705  / 11 Years ago, wed, june 26, 2013, 12:00:00

I want to convert a data:image encoded with base64 to a normal image file. So far my code looks like this:



this.toDataURL = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
ctx.drawImage(layer0, 0, 0);
ctx.drawImage(layer1, 0, 0);
ctx.drawImage(layer2, 0, 0);
var url = canvas.toDataURL('image/png');
document.getElementById('canvascontent').value = url;
};


As you can see it creates an DataUrl that is afterwards displayed in an output(#cancascontent). The final output looks something like this:



data:image/png;base64,iVBORw0KGgo.................


My problem is that I need it necessarily decoded so that I can upload the images. My aim is that my javascript code displays the image in a new window like a normal image file. For example. like this:



http://example.com/images/pro_js_3e.png


How can I decode the base64 image?


More From » javascript

 Answers
19

You can convert the canvas to a Blob, and then upload that.



To convert to a Blob, try this script: https://github.com/blueimp/JavaScript-Canvas-to-Blob



Then you can use canvas.toBlob instead of canvas.toDataURL.



Then to upload it, you need to use FormData



canvas.toBlob(function(blob){
var form = new FormData(),
request = new XMLHttpRequest();

form.append(image, blob, filename.png);
request.open(POST, /upload, true);
request.send(form);
}, image/png);


This is un-tested, but should work.


[#77386] Tuesday, June 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
griffinr

Total Points: 242
Total Questions: 91
Total Answers: 105

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
;