之前有遇到过一个要用多张图片合成gif图的场景,当时是搜索了好久,也没有发现有相关的使用记录。后来找到了实现方式,特此记录。
使用了Github上该project:android-gif-encoder,代码链接见页尾。
主要代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
/**
* 生成gif图
*
* @param file_name 保存文件名
* @param delay 帧之间间隔的时间
*/
private void createGif(String file_name, int delay) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
AnimatedGifEncoder localAnimatedGifEncoder = new AnimatedGifEncoder();
localAnimatedGifEncoder.start(baos);//start
localAnimatedGifEncoder.setRepeat(0);//设置生成gif的开始播放时间。0为立即开始播放
localAnimatedGifEncoder.setDelay(delay);
if (pics.isEmpty()) {
localAnimatedGifEncoder.addFrame(BitmapFactory.decodeResource(getResources(), R.drawable.pic_1));
localAnimatedGifEncoder.addFrame(BitmapFactory.decodeResource(getResources(), R.drawable.pic_2));
localAnimatedGifEncoder.addFrame(BitmapFactory.decodeResource(getResources(), R.drawable.pic_3));
} else {
for (int i = 0; i < pics.size(); i++) {
// Bitmap localBitmap = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(pics.get(i)), 512, 512);
localAnimatedGifEncoder.addFrame(BitmapFactory.decodeFile(pics.get(i)));
}
}
localAnimatedGifEncoder.finish();//finish
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/GIFMakerDemo");
if (!file.exists()) file.mkdir();
String path = Environment.getExternalStorageDirectory().getPath() + "/GIFMakerDemo/" + file_name + ".gif";
Log.d(TAG, "createGif: ---->" + path);
try {
FileOutputStream fos = new FileOutputStream(path);
baos.writeTo(fos);
baos.flush();
fos.flush();
baos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
gif_image.setImageURI(Uri.parse(path));
Toast.makeText(MainActivity.this, "Gif已生成。保存路径:\n" + path, Toast.LENGTH_LONG).show();
}
|
需要源码的同学看这里