How to retrieve image dimensions from url

Hey, I am trying to retrieve the image dimensions on upload or from a url (width and height), so that I can show the most of an image in square containers. (ie if if width > height, then set max image width to width, else set max image height to height. Could anyone help me with the javascript required to do this? My javascript sometimes returns a number, but sometimes doesn’t (I also have a promise version (at bottom) - which returns nothing:

// Create a new Image object
let img = new Image();

// Set the src of the image
img.src = “https://bookface-images.s3.amazonaws.com/small_logos/fc9ee3eaacb6de80432b68ad5b64b9e84bf8f77a.png”;

// Use the ‘onload’ event to get the dimensions when the image is loaded
img.onload = function() {
let width = this.width;
let height = this.height;

// Log the dimensions
console.log('Width: ' + width + ', Height: ' + height);

};

// Return the Image object
return img.width;

******PROMISE VERSION

// Create a new Promise
let imgLoadPromise = new Promise((resolve, reject) => {
// Create a new Image object
let img = new Image();

// Set the src of the image
img.src = "https://bookface-images.s3.amazonaws.com/small_logos/fc9ee3eaacb6de80432b68ad5b64b9e84bf8f77a.png";

// Use the 'onload' event to get the dimensions when the image is loaded
img.onload = function() {
    let width = this.width;
    let height = this.height;

    // Log the dimensions
    console.log('Width: ' + width + ', Height: ' + height);

    // Resolve the Promise with the width of the image
    resolve(width);
};

// If there is an error loading the image, reject the Promise
img.onerror = function() {
    reject(new Error("Could not load image at " + img.src));
};

});

// Return the Promise
return imgLoadPromise;

the first thing is that you want to add all your listeners before setting the image src or you risk to miss the events. the second thing is that you need to wait for the load event or you can’t be sure that the image has dimensions, so the first solution is a no go.

1 Like

thanks!

1 Like