完美解决Java处理读取gif图片报错:ArrayIndexOutOfBoundsException: 4096 while reading gif file (支持png、jpg、gif)

1、导入支持解析GIF的pom

<dependency>
   <groupId>com.madgag</groupId>
   <artifactId>animated-gif-lib</artifactId>
   <version>1.4</version>
</dependency>

2、简单粗暴直接贴上代码

package com.lezu.springboot.utils;

import cn.hutool.core.img.gif.GifDecoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImgUtil {

    private static final List<String> imgTypes = Arrays.asList("gif", "GIF");

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis(); //获取开始时间
        // String mp3 = "http://images01.mopimg.cn/imgs/20200616/20200616_d183df72adbae639847298a4f41f09d4.JPEG";
        String mp3 = "https://i-blog.csdnimg.cn/blog_migrate/721f6265333d8991541da95bdaa29e7c.gif";
        try {
            Map<String, Object> urlFileInfo = getUrlFileInfo(mp3);
            System.out.println(urlFileInfo.get("size"));//图片大小
            System.out.println(urlFileInfo.get("imageWidth"));//图片宽
            System.out.println(urlFileInfo.get("imageHeight"));//图片高
            System.out.println(urlFileInfo.get("fileSuffix"));//图片类型(也就是后缀名)
            System.out.println(urlFileInfo.get("fileName"));//图片名字
            long endTime = System.currentTimeMillis(); //获取结束时间

            System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间
        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println(e.getMessage());
        }
    }

    public static Map<String, Object> getUrlFileInfo(String urlPath) throws Exception {
        if (urlPath == null || urlPath.trim().length() == 0) {
            return null;
        }
        Map<String, Object> info = new HashMap<String, Object>(16);
        try {
            // first Exception
            URL url = new URL(urlPath);
            BufferedImage imageRead = formatImg(url);

            info.put("imageWidth", imageRead.getWidth());
            info.put("imageHeight", imageRead.getHeight());
            byte[] array = new byte[1024];
            // third Exception --IOException
            InputStream inputStream = url.openStream();
            int size = 0;
            int length = 0;
            // fourth Exception --IOException
            while ((length = inputStream.read(array)) != -1) {
                size += length;
            }
            info.put("size", size);
            int lastIndex = urlPath.lastIndexOf(".");
            if (lastIndex < urlPath.length() - 1) {
                info.put("fileSuffix", urlPath.substring(lastIndex + 1));
            }
            String fileString = url.getFile();
            if (fileString.length() > 0) {
                if (fileString.contains(File.separator)) {
                    info.put("fileName", fileString.substring(fileString.lastIndexOf(File.separator) + 1));
                } else if (fileString.contains("/")) {
                    info.put("fileName", fileString.substring(fileString.lastIndexOf("/") + 1));
                } else {
                    info.put("fileName", "未知文件");
                }
            }
            return info;
        } catch (MalformedURLException e) {
            throw new Exception("url缺少通信协议,请检查url是否正确");
        } catch (IOException e) {
            throw new Exception("网络位置的文件不存在,请检查url是否正确");
        }
    }

    /**
     * 判断当前图片是gif还是普通图片进行处理
     *
     * @param url
     * @return
     */
    private static BufferedImage formatImg(URL url) {
        BufferedImage imageRead = null;
        InputStream istream = null;
        try {
            String urlPath = url.getPath();
            int lastIndex = urlPath.lastIndexOf(".");
            if (lastIndex < urlPath.length() - 1) {
                urlPath = urlPath.substring(lastIndex + 1);
            }
            if (imgTypes.contains(urlPath)) { //判断是否属于gif图片
                //这块是通过GifDecoder来处理gif图片
                GifDecoder decoder = new GifDecoder();
                istream = url.openStream();
                //通过GifDecoder去读取gif图片
                decoder.read(istream);
                //获取图片
                imageRead = decoder.getImage();
            } else { //普通图片
                imageRead = ImageIO.read(url);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (istream != null) {
                    istream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return imageRead;
    }
}

GIF

png

总结一下:读取GIF图片的原理还是把gif变成了一帧来解析的

听不懂?没关系~~

打个比方比如你现在打开的图片是gif动态图片,你可以使用一下截图工具这样图片就被定住了 这叫一帧 你每打开一次截图工具它就是一帧。

posted @ 2021-05-21 14:50  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源