Skip to content

Instantly share code, notes, and snippets.

@jamalnasir
Last active March 7, 2018 11:03
Show Gist options
  • Save jamalnasir/0aa47cc5af4098719a9f753d724f060e to your computer and use it in GitHub Desktop.
Save jamalnasir/0aa47cc5af4098719a9f753d724f060e to your computer and use it in GitHub Desktop.
Javascript Snippet to Read an Image Object
$('#file-input').change(function(e){
var files = e.target.files;
for (var i = 0, f; f = files[i]; i++) {
if(f.type){
var image_types = ['image/png', 'image/jpg', 'image/jpeg'];
if((f.type && image_types.indexOf(f.type) < 0)) {
alert('Invalid file selected. Supported formats are jpeg and png.');
$(this).val('');
} else {
readURL(f, $('.image-preview'));
}
}
}
});
function readURL(file, preview) {
var reader = new FileReader();
reader.onload = function (e) {
preview.attr('src', e.target.result).fadeIn('fast');
var image = new Image();
image.src = preview.prop('src');
};
reader.readAsDataURL(file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment