If only a few file types like images should be supported you can write a function checking for "magic bytes".
Such a function will usually read a fixed number of bytes from the beginning of the file and search for the magic bytes at file type specific positions.
The Linux
file command provides such checks using a file named
magic that defines the search patterns. This file can be used as starting point for your checks.
Some image file definitions:
0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
0 string GIF8 GIF image data
0 beshort 0xffd8 JPEG image data
0 string MM\x00\x2a TIFF image data, big-endian
0 string II\x2a\x00 TIFF image data, little-endian
The format is quite simple:
The first value is the offset, the second the data type, and the third the data (with strings using C style where \xNN indicates a hex byte and \NNN an octal byte).
Howerver, these checks might still fail.