ImageIO读取gif历史遗留问题

过去的,未来的
2024-06-28 / 0 评论 / 0 点赞 / 35 阅读 / 265 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-06-28,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

使用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();

0

评论区