import cn.hutool.core.img.gif.AnimatedGifEncoder;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GIF_ {
public static void main(String[] args) throws IOException {
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start("C:/Users/503259716/Desktop/www/gif.gif");
encoder.setTransparent(Color.WHITE);
encoder.setRepeat(0); // 0 表示无限循环
encoder.setDelay(2); // 增加延迟到100毫秒,使动画更慢
// 创建一个BufferedImage实例,用于绘制每一帧
int width = 400, height = 200;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
// 加载一个支持中文的字体(确保路径正确,并且字体文件存在)
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("C:/Users/503259716/Desktop/www/simsun.ttc"));
font = font.deriveFont(Font.PLAIN, 24); // 设置字体大小和样式
g2d.setFont(font);
// 准备要显示的文字列表
String[] texts = {"北京烤鸭",
"兰州牛肉面",
"过桥米线",
"西湖醋鱼",
"南京盐水鸭",
"延吉冷面",
"烤羊肉串",
"刀削面",
"武汉热干面",
"手抓肉",
"亲自给你下厨"
};
// 绘制帧
for (int i = 0; i < 100; i++) { // 假设我们创建100帧
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height); // 清除背景(如果需要的话)
// 计算当前帧应该显示的文字
int textIndex = i % texts.length; // 循环使用文字列表
String text = texts[textIndex];
// 绘制文字(这里简单地将它放在图像的中心)
FontMetrics metrics = g2d.getFontMetrics();
int x = (width - metrics.stringWidth(text)) / 2;
int y = ((height - metrics.getHeight()) / 2) + metrics.getAscent();
g2d.setColor(Color.BLACK);
g2d.drawString(text, x, y);
// 将绘制好的帧添加到GIF编码器
encoder.addFrame(img);
// 这里不需要在每一帧后都释放Graphics2D资源,因为我们在循环结束后才释放
}
// 释放Graphics2D资源
g2d.dispose();
// 完成GIF编码
encoder.finish();
} catch (IOException | FontFormatException e) {
e.printStackTrace();
}
}
}
03-24