View Full Version : HTML5/javascript canvas interpreting base64 string as image

07-06-2011, 06:08 PM
Hi...I'm an HTML5 newb.

I was able to figure out how to convert an image to a base64 string and save the string for future viewing:
var oCanvas = document.getElementById("canvas");
oCanvas.toDataURL() //- this is a base64 encoded PNG file returned in URI format.
Canvas2Image.saveAsPNG(oCanvas, true) //- this returns an html <img> element which can be saved

So now I have a huge string: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABU[...I won't bore you with the stuff in the middle - but it's a really long string...]rkJggg==

How do I load that string up in a browser (I'm using Firefox 5.0) to display? I found several posts on Google referring to drawImage, and so this is what I have:
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;

// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
var image = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);

var dataURL = canvas.toDataURL("image/png");

return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

But all this does is return the string back to me when I call getBase64Image.

Any help would be so appreciated.

Thank you!

07-07-2011, 03:51 PM
You shouldn't need a canvas to do this: Firefox should interpret the string as the src of an img element just fine.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum