HTML5 - Submit & Preview Image

Recipe # | posted in Howto, Programming | Comments

1 – Problem Description

We need to submit an image and show it up directly to browser wrapped around canvas element.

2 – Solution

So, we will use HTML5 features like File API and fileReader to achieve this.

Here is the code:

<!doctype html>
<output id="imgOutput">
<input id="imgInput" type="file" accept="image/*" onchange="processFiles(this.files)">

<script>
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Great success! All the File APIs are supported.
} else {
  alert('The File APIs are not fully supported in this browser.');
}
function processFiles(files){
    // file is a FileList of File Objects
    var file = files[0];
    var reader = new FileReader();
    // Closure to capture the file information
    reader.onload = function (e) {
        // Create canvas element & render image
        var c=document.createElement('canvas');
        var ctx=c.getContext("2d");
        var img=new Image();
        img.onload = function(){
            c.width = this.width;
            c.height = this.height;
            ctx.drawImage(img,0,0);
        };
        // Image source
        img.src=e.target.result;
        // Insert image before <output>
        document.getElementById('imgOutput').insertBefore(c,null);
    };
    // Start reading the image
    reader.readAsDataURL(file);
}
</script>

At line 3, we have our input and we filter image files with accept="image/*".

If we want to submit multiple images, we can add multiple attribute.

After image submission, processFiles() is triggered.

Everything else is explained in the comments and  as always it is highly recommended to take a look at references. :)

Currently Safari and (of course) ie series does not fully support File API so this piece of code will not work. It was tested on Mozilla Firefox,Google Chrome and Opera successfully.

Demo available below:

3 – References

[1]  HTML5 multiple attribute

[2] Reading files in javascript using the file APIs

[3] HTML5 Canvas – Put an image on the canvas

Comments