Javascript - Return image dimensions

Asked

Viewed 890 times

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:

inserir a descrição da imagem aqui

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.

1 answer

1


Remember that the initial value of width is null and it will only be assigned at the event onload image. Note that the console.log(width); is out of this event. The ideal would be is inside. Correcting:

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;
            depois();
        };
        img.src = _URL.createObjectURL(file);
    }

    function depois(){
        console.log(width);
    }
});
  • So, this was purposeful, because inside I know it works, but I want to use the variables outside the onload event, it’s possible?

  • Yes I will edit....

  • 1

    As I already edited, I used a local Function.

  • Okay, I’ll test here, and comment on the result :)

  • It worked! Thank you!

  • You’re welcome, you just need to call!!!!....

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.