java diy生成GIF

    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();
            }
        }
    }
    

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值