利用java将jpg合成为gif

代码中需要的依赖:

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

代码:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.madgag.gif.fmsware.AnimatedGifEncoder;

public class Demo {
          
   

    // 存放jpg文件目录
    private final String path = System.getProperty("user.dir")+"\screenshot\";

    public static void main(String[] args) {
          
   
        try {
          
   
			AnimatedGifEncoder e = new AnimatedGifEncoder();
			e.setRepeat(0);
			e.start(path + "screenshot.gif");
			//获取目录下所有jpg文件
			String[] pic = new File(path).list();
			Assert.assertNotNull(pic);
			BufferedImage[] src = new BufferedImage[pic.length];
			for (int i = 0; i < src.length; i++) {
          
   
				e.setDelay(500); //设置播放间隔
				src[i] = ImageIO.read(new File(path+pic[i])); // 读入需要播放的jpg文件
				e.addFrame(src[i]);  //添加到帧中
			}
			e.finish();
		} catch (IOException e) {
          
   
			System.err.println("合成gif图失败");
		} 
    }
}
经验分享 程序员 微信小程序 职场和发展