Java根据图片生成GIF动图
合成gif的图片大小最好一致,不要问我为什么。
具体代码如下:
/** * 多张jpg图片合成一个gif * @author colorbin * 创建时间: 2017年4月8日 上午11:01:19 */ public class _jpgToGifUtil { public static void main(String[] args) { String[] pic = { "D://1.jpg","D://2.jpg"}; String newwPic = "D://1.gif"; int playTime = 200; jpgToGif(pic,newwPic,playTime); } /** * 把多张jpg图片合成一张 * @param pic String[] 多个jpg文件名 包含路径 * @param newPic String 生成的gif文件名 包含路径 * @param playTime int 播放的延迟时间 */ private synchronized static void jpgToGif(String pic[], String newPic, int playTime) { try { AnimatedGifEncoder e = new AnimatedGifEncoder(); e.setRepeat(0); e.start(newPic); BufferedImage src[] = new BufferedImage[pic.length]; for (int i = 0; i < src.length; i++) { e.setDelay(playTime); //设置播放的延迟时间 src[i] = ImageIO.read(new File(pic[i])); // 读入需要播放的jpg文件 e.addFrame(src[i]); //添加到帧中 } e.finish(); } catch (Exception e) { System.out.println( "jpgToGif Failed:"); e.printStackTrace(); } } }
前端代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> *{ margin: 0;padding: 0;} #bg_phone{ height: 517.5px;width: 375px;background: url(img/bg_1.png) no-repeat top center;margin: 0 auto; margin-top: 50px; background-size: 100%; } #bg_phone_back{ border: 0; width: 204px; height: 357px; background-color: #000000; overflow: hidden; position: relative; margin: 0 auto; margin-top: 100px; top: 54px; } </style> </head> <body> <div id="bg_phone"> <div id="bg_phone_back"> <div style="width: 204px;height: 287px; background: url(img/4a4c0d7af8b1df5a679a791c5c0d9337.gif) no-repeat top center; background-size: 100%;margin-top: 35px;"></div> </div> </div> </body> </html>