HowTo extract MimeType from a byte[] [duplicate]

Solution 1:

Try Java Mime Magic Library

byte[] data = ...
MagicMatch match = Magic.getMagicMatch(data);
String mimeType = match.getMimeType();

Solution 2:

I'm sure the library posted by @sfussenegger is the best solution, but I do it by hand with the following snippet that I hope it could help you.

DESCONOCIDO("desconocido", new byte[][] {}), PDF("PDF",
            new byte[][] { { 0x25, 0x50, 0x44, 0x46 } }), JPG("JPG",
            new byte[][] { { (byte) 0xff, (byte) 0xd8, (byte) 0xff,
                    (byte) 0xe0 } }), RAR("RAR", new byte[][] { { 0x52,
            0x61, 0x72, 0x21 } }), GIF("GIF", new byte[][] { { 0x47, 0x49,
            0x46, 0x38 } }), PNG("PNG", new byte[][] { { (byte) 0x89, 0x50,
            0x4e, 0x47 } }), ZIP("ZIP", new byte[][] { { 0x50, 0x4b } }), TIFF(
            "TIFF", new byte[][] { { 0x49, 0x49 }, { 0x4D, 0x4D } }), BMP(
            "BMP", new byte[][] { { 0x42, 0x4d } });

Regards.

PD: The best of it is that it doesn't have any dependency. PD2: No warranty about it's correctness! PD3: "desconocido" stands for "unknown" (in spanish)