Is there a way to infer what image format a file is, without reading the entire file?

Tom Kidd picture Tom Kidd · Sep 9, 2008 · Viewed 7k times · Source

Is there a good way to see what format an image is, without having to read the entire file into memory?

Obviously this would vary from format to format (I'm particularly interested in TIFF files) but what sort of procedure would be useful to determine what kind of image format a file is without having to read through the entire file?

BONUS: What if the image is a Base64-encoded string? Any reliable way to infer it before decoding it?

Answer

Greg Hewgill picture Greg Hewgill · Sep 9, 2008

Most image file formats have unique bytes at the start. The unix file command looks at the start of the file to see what type of data it contains. See the Wikipedia article on Magic numbers in files and magicdb.org.