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;