//Java API方式读取gif
final BufferedImage bufferedImage = ImageIO.read(new File(dir + "6.gif"));
//输出到新的文件
ImageIO.write(bufferedImage,"gif",new FileOutputStream(new File(dir + "6-out.gif")));
//发现6-out.gif变成了静态图片
原因 ImageIO.read(new File(dir + "6.gif")) 只读取到了gif文件第一帧图像
解决步骤:
1.引入hutool
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.11</version>
</dependency>
说明:若不想引入hutool,可以参见 https://github.com/rtyley/animated-gif-lib-for-java
https://github.com/rtyley/animated-gif-lib-for-java
2.逐帧读取gif文件
//这里模拟上传文件接口
final MockMultipartFile file = new MockMultipartFile("6.gif", new FileInputStream(new File(dir + "6.gif")));
GifDecoder d = new GifDecoder();
d.read(file.getInputStream());
int n = d.getFrameCount();
List<BufferedImage> frames = new ArrayList<>();
for (int i = 0; i < n; i++) {
BufferedImage frame = d.getFrame(i); // frame i
int t = d.getDelay(i); // display duration of frame in milliseconds
// do something with frame ,比如gif打水印,非法图片鉴定等
frames.add(frame);
}
3.输出新的gif
File output = new File(dir + "out/1919.gif");
AnimatedGifEncoder e = new AnimatedGifEncoder();
e.start(new FileOutputStream(output));
e.setDelay(1000 / 24); // 1 frame per sec
for (BufferedImage image : frames) {
e.addFrame(image);
}
e.finish();
本文介绍了如何使用Java处理GIF动画图像。通过Hutool库,实现了读取每一帧并输出新GIF的功能,解决了ImageIO.read()方法只能读取第一帧的问题。详细步骤包括引入Hutool库,逐帧读取并处理GIF,最后使用 AnimatedGifEncoder 类生成新的动画GIF。
1427

被折叠的 条评论
为什么被折叠?



