Search code examples
phpgdthumbnailsmime-typesexif

Is there any way to determine an image's type from its GD handle?


I am writing a thumbnailing script, and from what I've seen thumbnails tend to look best in the same format as their source. However, the script may be fetching images from the web, so I can't access the file twice. So is there any way to get the file type other than exif_imagetype and other functions that have to re-open the image? I don't want to rely on the extension as that can obviously be wrong.

I'm doing the thumbnail processing with GD, so something that uses the handle would be perfect, but I could also use the file's contents. And yes, I'm aware that GD handles reference uncompressed data, but I'm not sure that they don't remember what they decompressed from.


Solution

  • function getImageExt($bytes)
    {
        $hex_bytes = '';
        for ($i = 0; $i < strlen($bytes); $i++)
        {
            $hex_bytes .=  dechex(ord($bytes[$i]));
        }
        if (strncasecmp($hex_bytes,'FFD8',4) === 0) return 'jpg';
        if (strncasecmp($hex_bytes,'474946',6) === 0) return 'gif';
        if (strncasecmp($hex_bytes,'89504e47',8) === 0) return 'png';
        if (strncasecmp($hex_bytes,'424d',4) === 0) return 'bmp';
        return false;
    }