<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.9</version>
</dependency>
public class gif与png相互转换 {
//https://plus.hutool.cn/apidocs/
public static void main(String[] args) {
String s = gifToPng();
System.out.println("gif拆分成png:" + s);
pngToGif(s);
}
public static String gifToPng() {
List<String> list = new ArrayList<>();
GifDecoder d = new GifDecoder();
InputStream is = null;
OutputStream out =null;
try {
is = new FileInputStream("D:/photo/hutool/2.gif");
d.read(is);
for (int i = 0; i < d.getFrameCount(); i++) {
String imgName = (i + 1) + ".png";
BufferedImage frame = d.getFrame(i);
out = new FileOutputStream("D:/photo/hutool/" + imgName);
Img.from(frame).write(out);
out.flush();
out.close();
list.add("D:/photo/hutool/" + imgName);
}
is.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
return result;
}
/*
* 将png转成gif
* */
public static void pngToGif(String pngList) {
BufferedImage png =null;
try {
AnimatedGifEncoder e = new AnimatedGifEncoder();
e.setRepeat(0);
FileUtil.mkdir("D:/photo/hutool");
e.start("D:/photo/hutool/hecheng.gif");
String[] split = pngList.split(",");
for (String s:split) {
png = ImageIO.read(new File(s)); // 读入文件
//设置每一帧的间隔时间(ms)
e.setDelay(1000);
e.addFrame(png);
}
e.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
}