Reputation: 1452
I have the following code:
var checkImgDim=new Image();
checkImgDim.src=e.target.result;
if (input.files[0].size > MAX_SIZE)
setError("File too large - max 3MB");
else if (checkImgDim.naturalHeight < MIN_H ||
checkImgDim.naturalWidth < MIN_W)
setError("Image dimensions too small");
It works fine under Chrome however with Firefox I'm getting inconsistent results because it seems that naturalHeight and naturalWidth return 0 sometimes and there's a delay before the values are set. I don't want to load the image into the DOM or use .onload() the whole purpose of the code is simply to check the image dimensions. I don't think it would be good practice to add a time delay here. Can someone please tell me what the proper way to check the image dimensions?
Upvotes: 0
Views: 579
Reputation: 14123
You cannot get image size before it is loaded. You should use the load
event of the image anyway. Even if the image URL is actually a Data URI (e. g. if it comes from a FileReader
), it is “loaded” into the image object asynchronously.
It’s not necessary to insert the image as an HTML element into DOM for this. Just create a new Image
object, add a load
listener to it, and then set its src
property.
var image = new Image;
image.onload = function() {
alert(this.naturalHeight);
};
image.src = 'example.png';
If the image has already been downloaded before, it will not be downloaded again — its cached copy will be used instead (as long as client-side caching itself is not disabled intentionally via corresponding server-response headers). If the image URL is actually a Data URI, there is no downloading at all.
Note that naturalWidth
and naturalHeight
properties are relatively new and some browsers may not support them. So using regular width
and height
properties is currently more reliable, and they have the same values as long as their values have not been changed explicitly before.
Upvotes: 2
Reputation: 118
EDITED WITHOUT ONLOAD:
I think you can get the image dimensions before it's loaded by using a 0 second interval - it will technically return the dimensions before onload is called but this solution does use a delay like you said you wanted to avoid however I cannot think of another way of doing it. This way is at least quicker than onload.
var loaded = false;
var checkImgDim = new Image();
checkImgDim.onload = function () { loaded = true; };
var wait = setInterval(function () {
if (loaded) {
clearInterval(wait);
} else {
console.log(checkImgDim.naturalWidth, checkImgDim.naturalHeight);
}
}, 0);
Upvotes: 0