Java图片文件头校验

  1. JPEG- 文件头标识 (2 bytes): 0xff, 0xd8 (SOI) (JPEG 文件标识)- 文件结束标识 (2
    bytes): 0xff, 0xd9 (EOI)
  2. TGA- 未压缩的前5字节 00 00 02 00 00- RLE压缩的前5字节 00 00 10 00 00
  3. PNG- 文件头标识 (8 bytes) 89 50 4E 47 0D 0A 1A 0A
  4. (GIF- 文件头标识 (6 bytes) 47 49 46 38 39(37) 61,字符即: G I F
    8 9 (7) a
  5. BMP- 文件头标识 (2 bytes) 42 4D,字符即: B M
  6. TIFF- 文件头标识 (2 bytes) 4D 4D 或 49 49
  7. ICO- 文件头标识 (8 bytes) 00 00 01 00 01 00 20 20
  8. CUR- 文件头标识 (8 bytes) 00 00 02 00 01 00 20 20
public class UploadFileUtil {
    private final static Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);
    /**
     * 校验上传的东西是否为图片 GIF/JPG/PNG/BMP
     *
     * @param imgContent
     * @return
     */
    public static boolean checkImageTypeVailable(byte[] imgContent) {
        try {
            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) {
            logger.error("UploadFileUtil.检查文件类型错误:{}", e);
            return false;
        }
    }
}
发布了235 篇原创文章 · 获赞 221 · 访问量 96万+

猜你喜欢

转载自blog.csdn.net/drdongshiye/article/details/97686900
今日推荐