0

I'm allowing users to load their own image file from file system according to this post (last part - Images from the local file system)

https://stackoverflow.com/a/20285053

My Code

handleFiles: function (evt) {
        var file = evt.target.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function (e) {
            var contents = e.target.result;
            console.log(contents);

            //apply contents to src of img element
        };

    },

After getting the dataUri, I want to display the image on screen, however some images are bigger than the area in which I'm displaying them. Is there a way to check the size of the image given the dataUri (width and height) and resize is accordingly?

I am placing the dataUri in the 'src' attribute of image tag.

Community
  • 1
  • 1
erotavlas
  • 4,274
  • 4
  • 45
  • 104

1 Answers1

3

You can simply create an element in memory and read the value from it. Assuming "contents" is the dataURI of the image

handleFiles: function (evt) {
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = function (e) {
        var contents = e.target.result;
        console.log(contents);

        var memoryImg = document.createElement('img');
        memoryImg.src = contents;
        var width = memoryImg.width;
        var height = memoryImg.height;
    };
},

The element will be cleaned up as soon as the interpreter finishes your function.