ZeroZerg ZeroZerg - 7 days ago 5
CSS Question

How to get the size of the image which is uploaded by <input>



function changeFile() {
var preview = document.getElementById("previewDiv");
preview.style.backgroundImage = "";

var element = document.getElementById("ads_files");
var files = element.files;

var file = files[0];

console.log(file);

var reader = new FileReader();
reader.onload = loadFinished;
reader.readAsDataURL(file);

function loadFinished(event) {
var data = event.target.result;
preview.style.backgroundImage = 'url(' + data + ')';
}
}

#previewDiv {
border: 2px solid rgb(204, 204, 204);
width: 250px;
height: 200px;
background-size: 100% 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="ads_files" name="file" onchange=changeFile() />

<div id="previewDiv">
</div>





The code above is to upload a picture and show it as the background of div. It works perfectly.

Now I wish to upload the picture with proper width and height. So I need to get the size of the upload picture (The other pictures won't be uploaded to server).

I've searched some solutions on internet. It seems that document.getElementById("ads_files").value may get the path of the file after the image is uploaded. Then use Image.src=document.getElementById("ads_files") to load the image and get the size with function of Image.

But the question is that the value is a fake path like c:\fakepath\10256530_503531203106865_63236440322903725_n.jpg (I'm using Mac!!!!). Of course the program won't work.

I bet the work can be done locally but I don't know how to do it.

Any good idea?

Answer

Here is how you retrieve the image dimensions, add these to your loadFinished() function

var image = new Image();
image.src = data;
image.onload = function() {
    console.log(image.naturalWidth, image.naturalHeight);
}
Comments