Homan
Homan

Reputation: 26728

is there a way to detect what type of image is being loaded from an img src that is redirected?

I'm using the this facebook service to return profile pictures.

<img src="http://graph.facebook.com/username/picture">

If the fb user did not set a profile picture, the service redirects to this facebook anonymous person image: http://static.ak.fbcdn.net/rsrc.php/v2/yo/r/UlIqmHJn-SK.gif. I would like to avoid presenting those.

Is there a way, using javascript, to detect if the image returned is http://static.ak.fbcdn.net/rsrc.php/v2/yo/r/UlIqmHJn-SK.gif. That address is from a CDN, so I wonder if we can just check the file size is <= 390B and mime-type is image/gif?

EDIT: Unfortunately the solutions involving only modern browsers (HTML5 and canvas) might not work for me since the requirement is that we still need to support back to ie7.

Upvotes: 0

Views: 242

Answers (1)

Laurent Perrin
Laurent Perrin

Reputation: 14881

Yes there is, you can simply make your request with AJAX and parse the MIME-type yourself. Indeed, Facebook includes this header:

Access-Control-Allow-Origin: *

This authorizes CORS (Cross Origin Resource Sharing), which is now supported by most browsers.

If you absolutely must support old browsers, have a look at the Open Graph documentation:

https://developers.facebook.com/docs/reference/api/using-pictures/

Instead of directly fetching the picture, you can just fetch its metadata with JSONP. This should work in IE7:

function checkPictureUrl(userName, cb) {
  $.ajax({
    url: 'http://graph.facebook.com/' + userName + '/picture?redirect=false',
    dataType: 'jsonp',
    success: function (json) {
      // user only has a default profile picture
      if(json.data.is_silhouette)
        return cb(null);
      else
        return cb(null, json.data.url);
    },
    error: function (err) {
      cb(err);
    }
  });
}

Upvotes: 1

Related Questions