Skip to content

Commit

Permalink
保留图片 alpha channel 信息,设置 gif 透明背景,建议使用 png 图片源
Browse files Browse the repository at this point in the history
  • Loading branch information
hellodk34 committed May 5, 2022
1 parent a7abb99 commit 27db7e3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
Binary file removed app.jar
Binary file not shown.
14 changes: 14 additions & 0 deletions src/main/java/MainService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cn.hutool.core.img.gif.AnimatedGifEncoder;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
Expand Down Expand Up @@ -44,11 +45,24 @@ public void jpg2gif(String imgFolder, String outputFolder) throws Exception {
File[] tempList = file.listFiles();
if (tempList != null && tempList.length > 0) {
for (int i = 0; i < tempList.length; i++) {
// TODO 处理一下图片的 alpha channel 问题,保存原本的透明背景
File tempFile = tempList[i];
String tempFileName = tempFile.getName();
BufferedImage src = ImageIO.read(tempFile);
AnimatedGifEncoder gifEncoder = new AnimatedGifEncoder();
// 循环模式,0代表无限循环
gifEncoder.setRepeat(0);

// 保留原图的 alpha channel 信息,设置 gif 背景图为透明
/**
* new rgba color
* red
* green
* blue
* alpha
* 255,255,255 是白色 效果差强人意(勉强使人满意)
*/
gifEncoder.setTransparent(new Color(255, 255, 255, src.getColorModel().getTransparency()), true);
int lastDot = tempFileName.lastIndexOf('.');
String newFileName = tempFileName.substring(0, lastDot) + ".gif";
System.out.println("current sequence is " + (i + 1) + " and output file name is " + newFileName);
Expand Down

0 comments on commit 27db7e3

Please sign in to comment.