I have an image upload form with image preview. When a user selects an image from their desktop, the image is displayed in the preview before upload. I want to get the width of that image if possible but I don’t know how to get it. I have the following code:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result).css('width', ???);
};
reader.readAsDataURL(input.files[0]);
}
}
}
I have ??? in where I want to get the selected image width. Do you have any ideas how to do that?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Get image width using File API</title>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
console.log("The width of the image is " + img.width + "px.");
};
img.src = reader.result;
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
Basically you create a new image, set its src attribute to what is returned by reader.result, then use the image’s onload method to access its properties.