android使用多张图片合成gif文件

Sanchi

之前有遇到过一个要用多张图片合成gif图的场景,当时是搜索了好久,也没有发现有相关的使用记录。后来找到了实现方式,特此记录。
使用了Github上该project:android-gif-encoder,代码链接见页尾。

主要代码如下:

/**
 * 生成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();
}

需要源码的同学看这里

阅读 10.3k

share
我也是个菜鸟。希望大家都不会跟我一样走弯路~

0100100100100111011011010010000001110111011010010111010001101000001000000111100101101111011101010...

361 声望
14 粉丝
0 条评论

0100100100100111011011010010000001110111011010010111010001101000001000000111100101101111011101010...

361 声望
14 粉丝
文章目录
宣传栏