美文网首页
图片格式校验

图片格式校验

作者: leemien | 来源:发表于2020-04-24 18:38 被阅读0次

    public static boolean checkImageTypeVailable(File file) {
    if (file == null) {
    return false;
    }
    try {
    byte[] imgContent = FileUtils.readFileToByteArray(file);
    int len = imgContent.length;
    byte n1 = imgContent[len - 2];
    byte n2 = imgContent[len - 1];
    byte b0 = imgContent[0];
    byte b1 = imgContent[1];
    byte b2 = imgContent[2];
    byte b3 = imgContent[3];
    byte b4 = imgContent[4];
    byte b5 = imgContent[5];
    byte b6 = imgContent[6];
    byte b7 = imgContent[7];
    byte b8 = imgContent[8];
    byte b9 = imgContent[9];

            //GIF(G I F 8 7 a)  
            if (b0 == (byte)'G' && b1 == (byte)'I' && b2 == (byte)'F' && b3 == (byte)'8' && b4 == (byte)'7' && b5 == (byte)'a') {  
                return true;  
            //GIF(G I F 8 9 a)  
            } else if (b0 == (byte)'G' && b1 == (byte)'I' && b2 == (byte)'F' && b3 == (byte)'8' && b4 == (byte)'9' && b5 == (byte)'a') {  
                return true;  
            //PNG(89 P N G 0D 0A 1A)  
            }else if (b0 == -119 && b1 == (byte)'P' && b2 == (byte)'N' && b3 == (byte)'G' && b4 == 13 && b5 == 10 && b6 == 26) {  
                return true;  
            //JPG JPEG(FF D8 --- FF D9)  
            } else if (b0 == -1 && b1 == -40 && n1 == -1 && n2 == -39){  
                return true;  
            } else if (b6 == (byte)'J' && b7 == (byte)'F' && b8 == (byte)'I' && b9 == (byte)'F'){  
                return true;  
            } else if (b6 == (byte)'E' && b7 == (byte)'x' && b8 == (byte)'i' && b9 == (byte)'f'){  
                return true;  
            //BMP(B M)  
            } else if (b0 == (byte)'B' && b1 == (byte)'M') {  
                return true;  
            }else {  
                return false;  
            }  
        } catch (ArrayIndexOutOfBoundsException e) {  
            return false;  
        } catch (IOException e) {  
            return false;  
        }  
    }  

    相关文章

      网友评论

          本文标题:图片格式校验

          本文链接:https://www.haomeiwen.com/subject/kkkqwhtx.html