多張圖片生成gif圖
阿新 • • 發佈:2019-01-29
之前專案要求把png圖片合成gif的,在網上找的方法。僅當筆記記錄,沒備註,大佬勿噴。
private IdentityHashMap pics = new IdentityHashMap();
/** * 生成gif圖 * * @param file_name 儲存檔名 * @param delay 幀之間間隔的時間 */ private void createGif(String file_name, int delay) { Bitmap b1 = BitmapUtils.getBitmap(this, "15/1"); Bitmap b2 = BitmapUtils.getBitmap(this, "15/2"); Bitmap b3 = BitmapUtils.getBitmap(this, "15/3"); Bitmap b4 = BitmapUtils.getBitmap(this, "15/4"); Bitmap b5 = BitmapUtils.getBitmap(this, "15/5"); Bitmap b6 = BitmapUtils.getBitmap(this, "15/6"); Bitmap b7 = BitmapUtils.getBitmap(this, "33/7"); Bitmap b8 = BitmapUtils.getBitmap(this, "33/8"); 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(b1); localAnimatedGifEncoder.addFrame(b2); localAnimatedGifEncoder.addFrame(b3); localAnimatedGifEncoder.addFrame(b4); localAnimatedGifEncoder.addFrame(b5); localAnimatedGifEncoder.addFrame(b6); // localAnimatedGifEncoder.addFrame(b7); // localAnimatedGifEncoder.addFrame(b8); } else { for (int i = 0; i < pics.size(); i++) { // Bitmap localBitmap = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(pics.get(i)), 512, 512); localAnimatedGifEncoder.addFrame(BitmapFactory.decodeFile((String) 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(); LogUtils.e("Gif已儲存:"); } catch (IOException e) { e.printStackTrace(); LogUtils.e("Gif儲存失敗" + e); } ivCover.setImageURI(Uri.parse(path)); LogUtils.e("Gif已生成。儲存路徑:" + path); Toast.makeText(MainActivity.this, "Gif已生成。儲存路徑:\n" + path, Toast.LENGTH_LONG).show(); }