2011/03/29

HTML5 canvas: loading an image from a local file

HTML5 Canvas API Image accepts only URLs as source. We may not pass a file:// URL if our page is loaded from a server, so how to load a local picture into an Image object?

The trick is using the Data URI format. This format encodes the binary file data as a valid URL, yet does not point to anywhere, it is the data itself.

End-to-end example:


function loaded_picture2(evt)
{
Alert("loaded!");
// at this point you can paint or manipulate the image
// it can be referred at evt.target
}

function loaded_picture(evt)
{
var data = evt.target.result;

var pict = new Image();
pict.onload = loaded_picture2;
pict.src = data; // in URL data format
}

function load_picture(evt)
{
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = loaded_picture;

// reads in desired format that Image will acept
reader.readAsDataURL(f);
}

function init()
{
// pictfile is an input type="file" HTML element in page
document.getElementById("pictfile").addEventListener('change',
load_picture, false);
}

window.onload = init;
blog comments powered by Disqus