I need to display the image size in kilobyte and the dimension (height, width) using javascript/jquery. I came across few similar posts, but none could help me. I have two set of codes, that work separately. I can't figure out how to put them together.
This is the html code:
<span id="preview"></span>
<input type="file" id="file" onchange="displayPreview(this.files);"/>
This piece of code checks for file size & previews the image:
function onFileLoad(e) {
$('#preview').append('<img src="'+e.target.result +'"/>');
}
function displayPreview(files) {
var reader = new FileReader();
reader.onload = onFileLoad;
reader.readAsDataURL(files[0]);
fileSize = Math.round(files[0].size/1024);
alert("File size is "+fileSize+" kb");
}
This piece of code checks for file size:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
Please help me to put these codes together and display both the size and dimension together.
All you have to do to use the two codes is to combine them in the
displayPreview
function. You can create the image object that will append to thepreview
and find it's size, width, and height all in the same function.How to get image width and height using jquery
Find out the image width and height during image upload using jQuery
Size and dimension of upload image file
You can try like this
HTML
JQUERY
Both methods
Jsfiddle http://jsfiddle.net/code_snips/w4y75/ Jsfiddle http://jsfiddle.net/code_snips/w4y75/1/