1
Explanation
Hello guys, 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 upada, so I can manipulate it. Giving a console.log()
in the variable arq
, can only visualize the URL created for that image, and giving another console.log()
in the e.target.files[0]
I get some properties, as shown below:
But from none of these properties I can extract the dimensions, width and height from the image.
Attempt - Possible solution
Searching, I found this article of stackoverflow that shows a simple solution, however, the guy gives a alert()
in width and height, I tried to assign values to 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);
});
This way is not working, I would like ideas on how to solve, in the article I posted as link, there is a fiddle demonstrating the operation with alert();
, but I want to assign the values to some variables so I can manipulate them later.
Thank you!
Obs:
The console.log()
was put out of the event on purpose, because I want to use the variables outside this.
So, this was purposeful, because inside I know it works, but I want to use the variables outside the onload event, it’s possible?
– Thomerson Roncally
Yes I will edit....
– Matheus Cristian
As I already edited, I used a local Function.
– Matheus Cristian
Okay, I’ll test here, and comment on the result :)
– Thomerson Roncally
It worked! Thank you!
– Thomerson Roncally
You’re welcome, you just need to call!!!!....
– Matheus Cristian