Java8 BufferedImage无法读取tiff格式图片问题解决

937 阅读1分钟

起因

项目中有对图片进行拼接的需求,但是在使用BufferedImage读取“JPG”格式的图片报了控制正异常,网络搜寻了许久,没有找打bufferedImage读取JPG会报错的问题,遂想起来可能是文件出了问题

推荐一个小工具(文件格式识别工具):ttl7.pc6.com/wgd/FormatV…

使用工具打开一看:

图片原来是tiff格式编码的图片,查了一下资料,Java8及之前BufferedImage是不支持tiff格式的文件的,从Java9才开始支持,详见:openjdk.java.net/jeps/262,相关…

Motivation
The Image I/O Framework (javax.imageio), which is part of Java SE, provides a standard way to plug-in image codecs. Codecs for some formats, e.g. PNG and JPEG, must be provided by all implementations. A widely-used format, TIFF, is missing from this set. There have been multiple requests over the years for this format, from developers representing both small and large ISVs. It is also more relevant now since OS X uses TIFF as a standard platform image format and we have been unable to support that to date.

Description
Suitable TIFF reader and writer plugins, written entirely in Java, were previously developed in the Java Advanced Imaging API Tools Project (javadoc). We will merge this into the JDK, alongside the existing Image I/O plugins. The package will be renamed to javax.imageio.plugins.tiff, since it will become a standard part of the Java SE specification. The XML metadata format name will be similarly renamed.

意思就是我们的图片处理组件中一直缺失tiff,有很多大小公司的开发都要求我们开发这个,我们在java9把它加入Java SE的标准规范中来,GOOD JOB! 但是问题是我用的是java8

解决

解决方式其实很简单,引入一个依赖即可

<dependency>
    <groupId>com.twelvemonkeys.imageio</groupId>
    <artifactId>imageio-tiff</artifactId>
    <version>3.6.4</version>
</dependency>

ImageIO 会自动搜索类路径下继承的接口和子类,因此不需要显示调用,完全无侵入也就是说原来的代码无需任何改动,搞定。