Is it possible to find the image file extension from its contents in an array of bytes?

Having an image file already saved in the database as a byte array, is it possible to find the image file extension from the contents of the byte array?

I can get an array of bytes from the database. I need to show the image file on the screen.

Before displaying it, I want to have an image file extension, for example .png , .jpg or .jpeg , etc.

+6
source share
2 answers

Most file formats have a β€œMagic Number” at the beginning as a pair of bytes that indicates which file it has.

GIF begins with "GIF89a" or "GIF87a", that is, bytes 47.49.46.38.39.61 or 47.49.46.38.37.61 (both hexadecimal)

JPEG starts with FF, D8 and ends with FF, D9

PNG starts at 89.50.4E, 47.0D, 0A, 1A, 0A

Learn more about magic numbers on Wikipedia.

In other formats, you can specify a magic number. Some do not.

+5
source

The Java Mime Magic Library (a Java library for defining MIME files or streams) can also help here.

https://github.com/arimus/jmimemagic

http://sourceforge.net/projects/jmimemagic/

+1
source

Source: https://habr.com/ru/post/976867/


All Articles