8

I'm trying to write a function that checks if the image URL is an actual image, if it is it will return true, or else it will return false,

something like that:

checkImage(imageURL){
  if imageURL.isReal{
    return true
 }
 return false
}

I have found alot of answers but they didnt really work as boolean functions

1
  • 2
    A "valid" URL can mean many things. I hope you mean "location of existing valid resource", specifically an image? A valid URL may otherwise mean a so-called well-constructed URL, one that is an URL but not necessarily one that points to a valid or even existing (then, now or whenever) resource. Commented Apr 27, 2019 at 12:19

5 Answers 5

15

The most elegant solution is using a XMLHttpRequest and check the response code. If it's 200, the image exists, if it's something different it's highly possible that the picture - or more precise the url in general - doesn't exist. Here's an example:

function checkImage(url) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.send();
  request.onload = function() {
    status = request.status;
    if (request.status == 200) //if(statusText == OK)
    {
      console.log("image exists");
    } else {
      console.log("image doesn't exist");
    }
  }
}
checkImage("https://picsum.photos/200/300");

Well, as I said this is more a general approach. If you want to be sure that it's actually an image, you can utilize the Image object's onerror and onload events.

function checkImage(url) {
  var image = new Image();
  image.onload = function() {
    if (this.width > 0) {
      console.log("image exists");
    }
  }
  image.onerror = function() {
    console.log("image doesn't exist");
  }
  image.src = url;
}
checkImage("https://picsum.photos/200/300");

Sign up to request clarification or add additional context in comments.

5 Comments

but this way also correct with link doesn't have image returned?
I like this answer. Just a note: I'd advise not to use "GET" for the request method, but use "HEAD" -- that's easier on both the server and the client. Of course there is the possibility, unfortunately, that a poorly implemented Web service will not implement "HEAD" for the same URL (which it should as per HTTP spec), but I'd like to think that if you do the right thing enough times, the wrong stuff straightens out.
@obscure thank you for the answer, but the function is console logging, I want it to return true or false just like in my example, and for some reason I cant change your code to do that, could you please write that as a boolean?
@Alexander did you figure it out how to return true boolean?
@Markus You need to make the function async and add Promise resolution to make it return boolean: async function checkImage(url) { var image = new Image(); return await new Promise((resolve, reject) => { image.onload = function() { if (this.width > 0) { console.log("image exists"); resolve(true); }else return false; } }); } let booleanStatus = await checkImage("picsum.photos/200/300");
14

You could possibly use the fetch API. A modern variant of XHR.

So like

async function checkImage(url){
     
     const res = await fetch(url);
     const buff = await res.blob();
    
     return buff.type.startsWith('image/')

}

By this

checkImage('https://example.com/notAnImage.txt') // false
checkImage('https://example.com/image.png') // true

4 Comments

wow this gem was hiding here!
Good solution but this will not work on node.js as it will return type to be text/html for some URL e.g miro.medium.com/max/1400/0*cI5eoFps4thgr01A.jpeg
Just fetching headers can be slightly quicker: res=await fetch(url,{method:'HEAD'})
@AkashKumarSeth just tested your link in node.js v19 and it returned image/jpeg.
3

You could use getResponseHeader of XMLHttpRequest to check the mime type of the successfully returned content of your request. In fact you can't know the content of the response only based upon the http success response code of your request.

The XMLHttpRequest method getResponseHeader() returns the string containing the text of a particular header's value. If there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. The getResponseHeader() method returns the value as a UTF byte sequence.


In this example, a request is created and sent, and a readystatechange handler is established to look for the readyState to indicate that the headers have been received; when that is the case, the value of the Content-Type header is fetched. If the Content-Type isn't the desired value, the XMLHttpRequest is canceled by calling abort().

var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();

client.onreadystatechange = function() {
  if(this.readyState == this.HEADERS_RECEIVED) {
    var contentType = client.getResponseHeader("Content-Type");
    if (contentType != my_expected_type) {
      client.abort();
    }
  }
}

All the best.

Comments

2

In react its quite simple. You could use the onError to set an Error state

const [hasError, setHasError] = React.useState(false);

if (hasError) {
    // Do something
}
return (
    <img
        src={url}
        alt="Bild der Immobilie"
        onError={() => setHasError(true)}
    />
);

Comments

0

To create a function that checks if a given URL points to an actual image, you can follow these general steps:

1.Fetch the URL

2.Check the Response as well as width of the image

3.Handle Errors

if the response code is 200 as well as the image exist with some dimension the we will return true else false

so to return the boolean value we have to return the promise , and i used resolve to return the false value because by using the reject that will throw an error .

const checkurl = async(url) => {
  return new Promise((resolve, reject) => {
    if (url.trim() == "") {
      resolve(false)
    }
    fetch(url).then(res => {
        const img = new Image();
        img.src = url;
        img.onload = () => {
          if (res.status == 200 && !(img.width == 0)) {
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
      .catch(e => {
        resolve(false)
      })
  })
}

Comments

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.