Using File API to generate thumbnail for image

HTML5 provides a easy and standard way to interact with local files using File API. This file api could be used to generating image preview as thumbnail before sending to server or other file manipulation such as restricting size of file size , checking file extension on the basis of mimetype.

To check that whether your browser support for file api, we can use this java script snippets as suggested by Eric Bidelman in this article:
// 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.');
}

In this post I am going to describe how to generate image thumbnail on web browser. So, firstly our html part, in which we have one input file type tag and a image element.

<input id="src" type="file" onchange="fileChange()" /> 
<img id="target" />

Then our java script part in which our script is written for reading file and display it as thumbnail.

<script>

function fileChange(){
var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);
}

function showImage(src,target) {
var fr=new FileReader();
// when image is loaded, set the source of the image on the image element
fr.onload = function(e) { target.src = this.result; };
// fill fileReader object with image data
fr.readAsDataURL(src.files[0]);
}
</script>

At this point we are able to read image from file and display it on client side.
For more information on file api.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s