制作GIF圖的小工具類,依賴Glide其中幾個類

前提:必須依賴Glide中的三個類,AnimatedGifEncoder、LZWEncoder、NeuQuant

缺點:圖片越多,生成的GIF尺寸越大,制作的時間更久

public class MakeGifUtil {

    /**
     * 將本地多張圖片制作為gif圖
     *
     * @param foldName 需要保存的gif所在目錄
     * @param filename 需要保存的gif文件名
     * @param paths    制作gif的圖片本地路徑
     * @param fps      圖片切換的速度,單位為毫秒
     * @param width    gif的寬度
     * @param height   gif的高度
     * @return gif最后的絕對路徑
     * @throws IOException
     */
    public static String createGifByPaths(String foldName, String filename, List<String> paths, int fps, int width, int height) throws IOException {
        List<Bitmap> bitmaps = new ArrayList<>();
        if (paths.size() > 0) {
            for (int i = 0; i < paths.size(); i++) {
                Bitmap bitmap = BitmapFactory.decodeFile(paths.get(i));
                bitmaps.add(bitmap);
            }
        }
        String path = createGifByBitmapList(foldName, filename, bitmaps, fps, width, height);
        return path;
    }

    public static String createGifByBitmaps(String foldName, String filename, List<Bitmap> bitmaps, int fps, int width, int height) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        AnimatedGifEncoder gifEncoder = new AnimatedGifEncoder();
        gifEncoder.start(baos);//start
        gifEncoder.setRepeat(0);//設置生成gif的開始播放時間。0為立即開始播放
        gifEncoder.setDelay(fps);
        LogUtil.println("開始制作GIF:" + DateUtil.longToMill(System.currentTimeMillis()));
        if (bitmaps.size() > 0) {
            for (int i = 0; i < bitmaps.size(); i++) {
                //縮放bitmap
                Bitmap resizeBm = BitmapUtil.resizeImage(bitmaps.get(i), width, height);
                gifEncoder.addFrame(resizeBm);
            }
        }
        gifEncoder.finish();//finish
        LogUtil.println("GIF制作完成:" + DateUtil.longToMill(System.currentTimeMillis()));
        String path = foldName + filename;
        FileOutputStream fos = new FileOutputStream(path);
        baos.writeTo(fos);
        baos.flush();
        fos.flush();
        baos.close();
        fos.close();
        return path;
    }

}

BitmapUtil:

//使用Bitmap加Matrix來縮放
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容