My aim is to determine whether or not I should use an image based on its dimensions. To achieve this, I came across a function on stack overflow that can retrieve the dimensions of an image just by using its URL.
Here is the code snippet they provided:
function getMeta(url){
var img = new Image();
img.onload = function(){
alert(this.width + " " + this.height)
};
img.src = url;
}
For my specific requirements, I needed to access and evaluate the width and height of the image, so I made some modifications. Here's what I changed:
function getMeta(url){
var img = new Image();
img.onload = function(){
return [this.width, this.height]
};
img.src = url;
}
Using this function, I created another function to process it:
function backgroundCss(url){
const dims = getMeta(url);
return (dims[0] >= 1000 && dims[1] >= 300) ? `url(${url})` : "none"
}
I called this function within my style attribute:
<Grid item xs={15} md={6} style={{
backgroundImage: backgroundCss(url)
}}>
Although I thought my approach was logical and free of errors, I kept encountering an error indicating that 'Image()' is not defined. Even attempting a slightly different approach led to the same issue:
const [imageText, setImageText] = React.useState(null);
function getMeta(url){
var img = new Image();
img.src = url;
if(imageText == null){
img.onload = () => setImageText((img.width >= 1000 && img.height >= 300) ? `url(${url})` : "none");
getMeta(url);
return false;
}
return imageText;
}
...
<Grid item xs={15} md={6} style={{
backgroundImage: getMeta(url)
}}>
Is my objective even achievable? Where did I make mistakes in my implementations?
Edit: Is this revised version heading in the correct direction?
function getMeta(url){
return new Promise((resolve) => {
var img = new Image();
img.onload = function(){
resolve([this.width, this.height]);
};
img.src = url;
})
}
function backgroundCss(url) {
getMeta(url).then((dims) => {
return (dims[0] >= 1000 && dims[1] >= 300) ? `url(${url})` : "none"
})
}