java distinguish image format GIF JPG

Original address: http://blog.csdn.net/kehengqun1/article/details/49252549 Thanks to the blogger for
judging whether the file is a GIF file
private boolean isGifFile(File file) {
    try {
        FileInputStream inputStream = new FileInputStream(file);
        int[] flags = new int[5];
        flags[0] = inputStream.read();
        flags[1] = inputStream.read();
        flags[2] = inputStream.read();
        flags[3] = inputStream.read();
        inputStream.skip(inputStream.available() - 1);
        flags[4] = inputStream.read();
        inputStream.close();
        return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B;
    } catch (FileNotFoundException e) {
        e.printStackTrace ();
    } catch (IOException e) {
        e.printStackTrace ();
    } catch (Exception e) {
        e.printStackTrace ();
    }
    return false;
}

Determine if the file is a JPG file
private boolean isJpgFile(File file){
    try {
        FileInputStream bin = new FileInputStream(file);
        int b[] = new int[4];
        b[0] = bin.read();
        b[1] = bin.read();
        bin.skip(bin.available() - 2);
        b[2] = bin.read();
        b[3] = bin.read();
        bin.close();
        return b[0] == 255 && b[1] == 216 && b[2] == 255 && b[3] == 217;
    } catch (FileNotFoundException e) {
        e.printStackTrace ();
    } catch (IOException e) {
        e.printStackTrace ();
    } catch (Exception e) {
        e.printStackTrace ();
    }
    return false;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326360462&siteId=291194637