Skip navigation.
 
mlRe: Determining datatype of image from data
FROM : Avi Cherry
DATE : Fri Jan 10 16:46:02 2003

At 12:27 AM +0100 1/11/03, Andreas Hoeschler wrote:
>we are using [NSData dataWithContentsOfFile:...] to store images in
>a database. When retrieving the data again we need to determine the
>datatype (GIF, JPG,...) of the image from the data in order to use
>the correct contentType for HTML generation. We thought of making
>use of NSFileWrapper and then [[wrapper preferredFilename]
>pathExtension] but serialized NSFileWrappers are not compatible
>between Cocoa and GNUstep. We do not want to add an additional
>column to the database table just to store the file extension. I
>checked NSImageRep but found nothing. Any ideas?


Magic Numbers.
(Almost) all image formats have a 'magic' number at the beginning of
the file, the first few bytes.  These are (supposed to be) unique to
the file format.  The 'file' command from the shell comes with a very
large database of magic numbers and the command itself is used for
identifying files based on their contents.  The database that it
comes with is /etc/magic, and the file format itself is documented as
a man page under magic (5).  If you really only need to tell a few
different formats apart, it might be easiest to just implement a
quick check for these tags at the beginning of your data.  As Scott
mentions, you could use the ImageMagik system, but it would add an
enormous amount of code to your project.

For example:

A gif starts with the string 'GIF8'
JPEGs start with a 'big endian' short int, '0xffd8'.
TIFFs start with 4 characters, either: 'MM\x00\x2a' or 'II\x2a\x00'
(big and little endian formats, respectively).
PNGSs start with the 4 characters '\x89PNG'.
Etc, etc...

Related mailsAuthorDate
mlDetermining datatype of image from data Andreas Hoeschler Jan 10, 15:28
mlRe: Determining datatype of image from data Scott Anguish Jan 10, 15:46
mlRe: Determining datatype of image from data Avi Cherry Jan 10, 16:46