使用AnimatedGifEncoder把png序列图合成gif 背景透明

使用各种工具,包括ps、screentogif等,转gif,要么背景不透明,要么ps给压缩导致konvajs渲染gif异常。

最后没办法使用AnimatedGifEncoder自己合成,从网上找了段代码,研究了下AnimatedGifEncoder内部的方法和属性,终于给合成出背景透明且能够在konvajs中渲染的gif图了。

上代码:

maven:

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

/**

     * 生成GIF图片
* @param files 原始PNG图片
* @param isPressed 是否被压缩,默认true
* @return
*/
public static File generatePreview(File[] files, Boolean isPressed) {
try {
BufferedImage[] images = null;
// if(isPressed)
// images = parseCompressed(files);
// else
images = parse(files);
Path path = Files.createTempFile("preview_", ".gif");
System.out.println(path);
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
// 设置循环模式,0为无限循环 这里没有使用源文件的播放次数
encoder.setRepeat(0);

encoder.start(new FileOutputStream(path.toFile()));
int count = 1;
//采样频率,数字越大,文件越小,丢失的帧越多,设置为1可保持原帧
int frequency = 2;
for (BufferedImage image : images) {
if((++count)%frequency==0){
encoder.setDelay(50*frequency);
encoder.setTransparent(new Color(Color.TRANSLUCENT),true);
encoder.addFrame(image);
}
}
encoder.finish();
System.out.print("GIF创建成功: ");
return path.toFile();
} catch (IOException e) {
System.out.println("failed to generate preview file");
throw new RuntimeException("failed to generate preview file");
}
}
private static BufferedImage[] parse(File[] files){
BufferedImage[] bi = new BufferedImage[files.length];
try {
for (int index = 0; index < files.length; index++) {
bi[index] = ImageIO.read(files[index]);
}
} catch (IOException e) {
System.out.println("fail to parse template");
throw new RuntimeException("fail to parse template", e);
}
return bi;
}
public static void main(String[] strs){
File[] files = new File("D:/test/test1").listFiles();
generatePreview(files,false);
}
 
posted @ 2020-09-04 10:03  昨夜忆星辰  阅读(1324)  评论(0编辑  收藏  举报