Check whether image exists on remote URL

Sometimes there is a situation where you need to display some default image if remote image URL does not exist. We have an application that shows up songs information from apple site and sometimes there is a missing artwork image. Our application needs to display some default image like “No Album Arwork Found” in case of missing image.

There is an easy way we can handle this situation.

<img src=”http://a1.phobos.apple.com/us/r10/Music/y2003/m3/d8/h0/s01.oeoonfsp.75×75-65.jpg” id=”myImg” onerror=”javascript:loadOther(this);” />

You can specify JavaScript onerror event that will be called if image specified to SRC attribute not found.

You can load default image in that javascript method like this…

function loadOther(me){
//amend your code here
me.src=”/itunes_art_unavailable.jpg”;
}

That’s easy…

Posted in Client Side Scripting Tagged with:
4 comments on “Check whether image exists on remote URL
  1. Cisco says:

    something I wrote up quickly this morning. Not fully tested, but seems to work ok. PHP method to check if an image exists on a remote url.

    function fCheckImageUrl($pUrl)
    {
    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $pUrl);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    // Getting binary data
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

    try {
    $image = curl_exec($ch);
    curl_close($ch);
    if($image)
    return true;
    return false;
    }
    catch (Exception $e)
    {
    curl_close($ch);
    return false;
    }
    curl_close($ch);
    }

  2. hananiel says:

    his is such an elegant solution. Glad you shared I was struggling with Server.Mappath for local images , this same strategy will work for all images.

    Also you can shorten this to

  3. Bharathi says:

    Hey.. This worked great for me.

    Thanks for posting it..

  4. kien says:

    A neat solution to a problem I have been struggling with for several hours. Thank you.

Ads