Android实现多张图片合成GIF

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u011102153/article/details/52122722

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

工具类:

public static String createGif(String filename, List<String> 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依赖。

image

image2

image3

详情请看源代码,需要改进的是一些参数的控制还没有提供给用户修改。

猜你喜欢

转载自blog.csdn.net/u011102153/article/details/52122722