views:

44

answers:

2

I am having a bit of trouble getting Gravatars to work properly:

When I request the following:

http://gravatar.com/avatar/8a17d0d0d8bdf6a8d527bbc943a17cf8.jpg?s=64&d=identicon

Firefox proudly displays the following:

...indicating that the file is a PNG image.

This confuses me - I thought Gravatars were JPEG images. It seems like they can be either. How can I find out if a given image is PNG or JPEG preferably without downloading it first?


Note: Some people are reporting that Gravatar only returns PNG images. Please explain this:

http://gravatar.com/avatar/03cd042b82ac85b2c5fe0757a94e0413?s=64&d=identicon
A: 

The end tag is JPG, but the string is interpreted by the server and the corresponding image is sent. In this case a PNG.

Josh K
Are *all* Gravatars PNG images, then? If not, how can I tell on an individual basis which format it is?
George Edison
They are all sent as PNGs.
John Gietzen
@George, yes they are all sent as PNG's.
Josh K
Please see my update above.
George Edison
@George: I thought they were all sent as PNG's. I guess some are and some aren't. I'm guessing the different type of gravatar would determine the type it sends.
Josh K
@Josh: How can I figure out which one I'm getting? I'm processing them with PHP's GD library, so I have to know ahead of time.
George Edison
+1  A: 

If Gravatar icons have accurate MIME types assigned by the server you're accessing them from, just check that. It should be image/jpeg for JPEGs and image/png for PNGs.

Failing that...

http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header

A PNG file starts with an 8-byte signature. The hexadecimal byte values are 89 50 4E 47 0D 0A 1A 0A; the decimal values are 137 80 78 71 13 10 26 10.

So just check the eight bytes at the beginning of the file; if it's a PNG, it'll have the stated values in those bytes, and if not, it won't. Just download the file, possibly store it somewhere temporarily (which shouldn't be too hard considering it shouldn't be too big), and process it differently depending on what the header contains. You can always change the file extension and then use PHP's graphics library if you saved it as the wrong type at first. (Or are you not allowed to do that?)


As a side note, my favorite bit about the PNG header:

50 4E 47 In ASCII, the letters PNG, allowing a person to identify the format easily if it is viewed in a text editor.

JAB
True. But don't JPEG files have `'JFIF'` in there somewhere? Anyway, thanks.
George Edison
@George: Not necessarily (though generally they do have the JFIF header). http://en.wikipedia.org/wiki/JPEG#JPEG_files It's just that the PNG header popped into my head first.
JAB