Not sure if that is possible but why don't just just also store the mime-type in the database?
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
For most image formats it should be possible to read the type from the first few bytes, but I still would store the image mime type or extension in the database instead.