使用ImageIO 读取文件报错,ArrayIndexOutOfBoundsException: 4096
public static void main(String[] args) {
try {
String path="/Users/pengtaofeng/Desktop/1/2.gif";
File file = new File(path);
BufferedImage read = ImageIO.read(file);
System.out.println(read.getHeight());
}catch (Exception e){
e.printStackTrace();
}
}
java.lang.ArrayIndexOutOfBoundsException: 4096
at com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:984)
at javax.imageio.ImageIO.read(ImageIO.java:1448)
at javax.imageio.ImageIO.read(ImageIO.java:1308)
at cn.fengpt.fengptifesle.controller.ImageTest.main(ImageTest.java:18)
解决方式一
1、先导入支持解析GIF的包。
<dependency>
<groupId>com.madgag</groupId>
<artifactId>animated-gif-lib</artifactId>
<version>1.4</version>
</dependency>
2、通过文件后缀判断是否是GIF图片,是GIF图片就采用GifDecoder来读取GIF图片
public BufferedImage getBufferedImage(String path) {
BufferedImage bufferedImage = null;
try {
String extension = FilenameUtils.getExtension(path);
if ("gif".equalsIgnoreCase(extension)) {
//通过GifDecoder来读取gif图片
GifDecoder decoder = new GifDecoder();
decoder.read(path);
bufferedImage = decoder.getImage();
}
else {
File file = new File(path);
bufferedImage = ImageIO.read(file);
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
return bufferedImage;
}
解决方式二
使用hutool工具类GifDecoder读取gif获取上传图片的宽和高
GifDecoder gifDecoder = new GifDecoder();
gifDecoder.read(file.getInputStream());
BufferedImage sourceImage = gifDecoder.getImage();
评论区