1

之前有遇到过一个要用多张图片合成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();
}

需要源码的同学看这里


Sanchi
364 声望14 粉丝

01001001001001110110110100100000011101110110100101110100011010000010000001111001011011110111010100101110