Android实现多张图片合成GIF 【转】

工程地址:https://github.com/LineChen/GifMaker

工具类:

public static String createGif(String filename, List paths, int fps, int width, int height) throws IOException {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            AnimatedGifEncoder localAnimatedGifEncoder = new AnimatedGifEncoder();
            localAnimatedGifEncoder.start(baos);//start
            localAnimatedGifEncoder.setRepeat(0);//设置生成gif的开始播放时间。0为立即开始播放
            localAnimatedGifEncoder.setDelay(fps);
            if (paths.size() > 0) {
                for (int i = 0; i < paths.size(); i++) {
                    Bitmap bitmap = BitmapFactory.decodeFile(paths.get(i));
                    Bitmap resizeBm = ImageUtil.resizeImage(bitmap, width, height);
                    localAnimatedGifEncoder.addFrame(resizeBm);
                }
            }
            localAnimatedGifEncoder.finish();//finish

            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/LiliNote");
            if (!file.exists()) file.mkdir();
            String path = Environment.getExternalStorageDirectory().getPath() + "/LiliNote/" + filename + ".gif";
            FileOutputStream fos = new FileOutputStream(path);
            baos.writeTo(fos);
            baos.flush();
            fos.flush();
            baos.close();
            fos.close();

        return path;
    }

主要参数:图片地址集合、GIF播放每张图片的时间间隔、宽度、高度。

方法中最重要的类是AnimatedGifEncoder,这个类在Glide图片加载库中有,所以工程中也添加了Glide依赖。

你可能感兴趣的:(Android实现多张图片合成GIF 【转】)