0

I'm having issues reading sizes with file reader. Have tried various browsers and files, width always comes back as 0.

    var fileReader = new FileReader();
    var img = new Image();

    fileReader.onload = function(event) {
        img.src = event.target.result;
        console.log(img.width);

    };

    fileReader.onerror = function() {

        //handle error
    };

    fileReader.readAsDataURL(file);

The file var is looped out from the following on a drag and drop event:

e.originalEvent.dataTransfer.files

2 Answers 2

3

maybe your image object is not loaded try this :

img.onload = function () {console.log(img.width)}
Sign up to request clarification or add additional context in comments.

3 Comments

Surely the fileReader on load event covers this, what's the difference between the two?
Generaly I use both. Because some time when you read the image file and then put the content in your javascript it's take some times so onload avoid this time laps problem.
@panthro "Surely the fileReader on load event covers this" No. You need both load events. codepen.io/tarabyte/pen/PmKwyK
3

I think you have an error while assigning binary data to Image.

Assigning image:

fileReader.onload = function(e) {
    var img = new Image();
    img.src = fileReader.result;
}

Demo:

document.getElementById('img').addEventListener('change', function(e) {
    var file = this.files[0];
    var fileReader = new FileReader();
    var img = new Image();

    fileReader.onload = function(event) {
        img.src = fileReader.result;
        
        img.onload = function() {
            console.log(img.width);
        }

        document.getElementById('result').appendChild(img);
    };
    fileReader.readAsDataURL(file);
})
<input id="img" type="file">
<div id="result"></div>

see codepen demo or jsfiddle

2 Comments

@panthro seems like all ok. Attached snippet
@Yury Tarabanko Thanks! Updated for Chrome

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.