Skip to content
Advertisement

Javascript, how can I get image width and height from a blob?

So this is my code snippet (unnecessary code lines are removed):

let imgInput = document.getElementById('id_photo');
imgInput.addEventListener('change', function (e) {
    if (e.target.files) {
        for (let i = 0; i < e.target.files.length; i++) {

        let imageFile = e.target.files[i];
        var reader = new FileReader();

        reader.onload = function (e) {
            var img = document.getElementById(nevermindID);
            img.onload = function() {
                var shape = resizeImage(img) // resizing image for future canvas drawing, returns [width, height] (resized)
                
                var canvas = document.createElement("canvas")
                canvas.width = shape[0]
                canvas.height = shape[1]
                var ctx = canvas.getContext("2d")
                ctx.drawImage(img, 0, 0, shape[0], shape[1])
                // converting to base64 logic and the rest code
            }
            img.src = e.target.result;
        }
        reader.readAsDataURL(imageFile);

    }
}
});

I want to get the uploaded original image’s width and height so I can resize it. I can’t do it from imageFile as it returns undefined and can’t get it from the img variable as it originally depends on my css (in css the <img> tag is in a <div> tag which is not fullscreen, let’s say it is 400 pixels). So correspondingly, if I upload 5000×5000 image it will not be the original-sized (hope you got it). My problem is that because my css resizes that div and elements inside, I can’t get normal width and height of my original image, so I can resize it then draw with canvas and then convert it to base64.

I try to add this code to img.onload:

var blobURL = URL.createObjectURL(imageFile)

Here I access my original image (which is imageFile), create blob for it and get that blob link. But I can’t access that blob link image’s width and height. Any suggestions?

Note: I think the problem is in img.onload itself. As in this line I pass that img:

ctx.drawImage(img, 0, 0, shape[0], shape[1])

FYI. This is how it looks when I upload my image. It is about 90×90 pixels here. And that causes the problem with canvas, as img.onload takes those dimensions (90×90) and not the original dimensions which is about 5000×5000 enter image description here

The resized image looks like: enter image description here

Edited:

If anyone is curious, I can paste my solved code version here so you can adjust to it. Leave a comment below.

Advertisement

Answer

You can use the Image constructor

const img = new Image();
img.src = imageDataUrl;
img.onload = () => {
   // img.width
   // img.height
 };
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement