I want to load an image file from the computer directly to any js object without using any server-side component. For example, I want to select a picture from the local mach
You can use createObjectURL method of the window.URL object, this doesn't have much browser support though
http://jsfiddle.net/LvAqp/ only works in chrome and firefox
Using the new File APIs, it is possible to access content from the local disk.
You put a traditional <input type="file">
upload field on your page, and handle the onchange
event.
MDN has a good writeup with all of the details.
Your event handler gets a FileList
containing Files
. From there, you can call FileReader.readAsDataURL(File) to fetch the content of the image and then pass that data URL to an <img>
or a <canvas>
to do rotation.
There is a way with HTML5, but it requires the user to have dropped the file into a drop target or used a <input type="file"/>
box, since otherwise it would be a security issue.
Using the File
API you can read files, and specifically you can use the FileReader.readAsDataURL
method to set the content as a data:
URL for the image tag.
Here's an example:
$('#f').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
console.dir(ev2);
$('#i').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});
http://jsfiddle.net/alnitak/Qszjg/