Java验证图片格式

来源:互联网 发布:床垫怎么选 知乎 编辑:程序博客网 时间:2024/05/21 10:47

图片的格式是通过魔数来表示的,而不是后缀名。也就是说,通过后缀名验证图片格式是不一定正确的。

  • 简单的获取图片格式的方法:
public String getImgType(byte[] imageDataArr) throws IOException {        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageDataArr);                MemoryCacheImageInputStream is = new MemoryCacheImageInputStream(bais);) {            Iterator<ImageReader> it = ImageIO.getImageReaders(is);            if (!it.hasNext()) {                throw new RuntimeException("非图片文件");            }            ImageReader reader = it.next();            return reader.getFormatName();        }    }
  • 较复杂的方式:
public String[] getImgType(byte[] imageDataArr) throws IOException {        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageDataArr);                MemoryCacheImageInputStream is = new MemoryCacheImageInputStream(bais);) {            Iterator<ImageReader> it = ImageIO.getImageReaders(is);            if (!it.hasNext()) {                throw new RuntimeException("非图片文件");            }            ImageReader reader = it.next();            return reader.getOriginatingProvider().getFormatNames();        }    }

一般图片只有一种格式,除非你实现了SPI,所以实际工作中我只用前一种获取图片格式的方式;后一种可以处理有多个格式的情况。

1 0
原创粉丝点击