Monday, January 9, 2012

Get mimetype from header file

// return: jpeg, png, bmp, unknown
public static String getMimeTypeFileByHeader(String realPath) 
{
    File f = new File(realPath);
    try {
        InputStream in = new FileInputStream(f);
       
        byte[] HEADERJPEG = new byte[] {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF};
        byte[] HEADERBMP = new byte[] { 0x42, 0x4d };
        byte[] HEADERPNG = new byte[] { (byte) 0x89, 0x50, 0x4e };

        byte[] header = new byte[3];
        int h = in.read(header);
       
        if (h==3 && Arrays.equals(header, HEADERJPEG)) {
            return "jpeg";
        }
       
        if (h==3 && Arrays.equals(header, HEADERPNG)) {
            return "png";
        }
       
        byte[] header2 = new byte[2];
        for (int i=0; i<2; i++)
            header2[i] = header[i];
       
        if (Arrays.equals(header2, HEADERBMP)) {
            return "bmp";
        }
       
    } catch (Throwable e) {}
   
    return "unknown";
}

// Others
/*
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 } });
*/

No comments:

Post a Comment

[ROM] Samsung S7 Stock Firmware BRI (Taiwan台灣)

Latest ROM: G930FXXU1DQEU Download: https://kfhost.net/tpl/firmwares.php?record=B7E6DE774E3811E7963AFA163EE8F90B Reference: http://...