Explanation
Hello everyone, I'm uploading an image with JavaScript , using the following code:$('#image-background').on("change", function(e) {
var arq = URL.createObjectURL(e.target.files[0]);
$("#mp-image-bg").attr("src", arq).css("display", "block");
});
I want to return the dimensions of the image up, so I can manipulate it. By giving console.log()
in variable arq
, I can only see the URL created for that image, and giving another console.log()
in e.target.files[0]
I get some properties, as shown below:
ButfromnoneofthesepropertiescanIextractthedimensions,widthandheightoftheimage.
Attempt-Possiblesolution
Looking,Ifound this stackoverflow article which shows a simple solution, however, the guy gives a alert()
in width and height, I tried assigning the values to the variables to use in the rest of my script and did not get a satisfactory result.
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img, width, height;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
width = this.width;
height = this.height;
};
img.src = _URL.createObjectURL(file);
}
console.log(width);
});
In this way it is not working, I would like ideas on how to solve, in the article that I posted as a link, there is a fiddle that demonstrates the operation with alert();
, but I want to assign the values to some variables to be able to manipulate them later.
Thank you!
Note:
The console.log()
was purposely put out of the event because I want to use the variables outside of this.