Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 取得影片縮圖的三種做法與取舍

編輯:關於 Android 程式設計

要在清單裡顯示影片預覽圖,Android 上大致有三條路:

  1. 從媒體庫(MediaStore)查詢
  2. API 8(Android 2.2)之後使用 ThumbnailUtils
  3. 透過 JNI 自行實作 MediaMetadataRetriever

三種方法的取捨

  • 媒體庫查詢:新加入的影片必須等 SD 卡重新掃描、寫入媒體庫之後才查得到縮圖,即時性差,穩定性也普通,適合簡單的展示場景。
  • ThumbnailUtils:實作最簡單,一行搞定,但 2.2 以下的版本沒有這個類別。
  • MediaMetadataRetriever:實作最麻煩,卻最靈活——能指定任意時間點抓幀,也能讀取完整的 metadata。多數需要客製的專案會走這條。

方法一:查詢媒體庫

public static Bitmap getVideoThumbnail(ContentResolver cr, String fileName) {
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inDither = false;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    // 以檔案路徑作為查詢條件
    String whereClause = MediaStore.Video.Media.DATA + " = '" + fileName + "'";
    Log.v(TAG, "where = " + whereClause);

    Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Video.Media._ID },
            whereClause, null, null);
    Log.v(TAG, "cursor = " + cursor);

    if (cursor == null || cursor.getCount() == 0) {
        return null;
    }
    cursor.moveToFirst();

    String videoId = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
    Log.v(TAG, "videoId = " + videoId);
    if (videoId == null) {
        return null;
    }
    cursor.close();

    long videoIdLong = Long.parseLong(videoId);

    // 以 ID 從縮圖表取出 MICRO_KIND 縮圖
    bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, videoIdLong,
            Images.Thumbnails.MICRO_KIND, options);
    Log.v(TAG, "bitmap = " + bitmap);
    return bitmap;
}

提醒:Cursor 記得關閉,建議改用 try/finally 或 use 之類的機制,避免例外時洩漏。

方法二:ThumbnailUtils

三個靜態方法就夠用:

// 1. 直接從影片檔產生縮圖
//    參數一為影片路徑,參數二為 MINI_KIND 或 MICRO_KIND,決定輸出品質
static Bitmap createVideoThumbnail(String filePath, int kind)

// 2. 對既有 Bitmap 做縮放,options 可傳 OPTIONS_RECYCLE_INPUT 以回收原始 Bitmap
static Bitmap extractThumbnail(Bitmap source, int width, int height, int options)

// 3. 同上,但沒有 options 參數
static Bitmap extractThumbnail(Bitmap source, int width, int height)

方法三:自己實作 MediaMetadataRetriever

MediaMetadataRetriever 在 framework 中被標記為 @hide,一般應用拿不到。 theoretically 你可以改 AOSP 原始碼、把 frameworks 中 MediaMetadataRetriever.java 的 @hide 拿掉並重新編譯 framework,但這顯然不適合一般 App 開發。實務上更常見的做法是在專案裡自己寫一份同名的類別,透過 JNI 去呼叫系統既有的 native 實作。

步驟一:取出 JNI 函式庫

開啟 SDK 的 Tools 目錄、執行 DDMS,在選單中選擇 Device → File Explorer,找到 /system/lib/libmedia_jni.so,點右上角把檔案 pull 出來。在 Eclipse 專案中建立 libs/armeabi 資料夾(新版工具為 src/main/jniLibs/armeabi),把 libmedia_jni.so 放進去。

步驟二:實作 MediaMetadataRetriever 類別

public class MediaMetadataRetriever
{
    static {
        System.loadLibrary("media_jni");
        native_init();
    }

    // 供 native 方法存取
    @SuppressWarnings("unused")
    private int mNativeContext;

    public MediaMetadataRetriever() {
        native_setup();
    }

    /** 設定運作模式,只需在物件的生命週期一開始呼叫一次 */
    public native void setMode(int mode);
    public native int getMode();

    /** 設定資料來源(檔案路徑) */
    public native void setDataSource(String path) throws IllegalArgumentException;

    /** 設定資料來源(FileDescriptor + 範圍) */
    public native void setDataSource(FileDescriptor fd, long offset, long length)
            throws IllegalArgumentException;

    /** 設定資料來源(FileDescriptor) */
    public void setDataSource(FileDescriptor fd) throws IllegalArgumentException {
        // 刻意小於 LONG_MAX
        setDataSource(fd, 0, 0x7ffffffffffffffL);
    }

    /** 設定資料來源(Content Uri) */
    public void setDataSource(Context context, Uri uri)
            throws IllegalArgumentException, SecurityException {
        if (uri == null) {
            throw new IllegalArgumentException();
        }
        String scheme = uri.getScheme();
        if (scheme == null || scheme.equals("file")) {
            setDataSource(uri.getPath());
            return;
        }
        AssetFileDescriptor fd = null;
        try {
            ContentResolver resolver = context.getContentResolver();
            try {
                fd = resolver.openAssetFileDescriptor(uri, "r");
            } catch (FileNotFoundException e) {
                throw new IllegalArgumentException();
            }
            if (fd == null) {
                throw new IllegalArgumentException();
            }
            FileDescriptor descriptor = fd.getFileDescriptor();
            if (!descriptor.valid()) {
                throw new IllegalArgumentException();
            }
            if (fd.getDeclaredLength() < 0) {
                setDataSource(descriptor);
            } else {
                setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength());
            }
            return;
        } catch (SecurityException ex) {
        } finally {
            try {
                if (fd != null) {
                    fd.close();
                }
            } catch (IOException ioEx) {
            }
        }
        setDataSource(uri.toString());
    }

    /** 取得指定 key 的 metadata 值 */
    public native String extractMetadata(int keyCode);

    /** 擷取一個代表幀,最常用來產生縮圖 */
    public native Bitmap captureFrame();

    /** 取得嵌入的專輯封面或圖像 */
    public native byte[] extractAlbumArt();

    /** 使用完畢後釋放 native 配置 */
    public native void release();

    private native void native_setup();
    private static native void native_init();
    private native final void native_finalize();

    @Override
    protected void finalize() throws Throwable {
        try {
            native_finalize();
        } finally {
            super.finalize();
        }
    }

    public static final int MODE_GET_METADATA_ONLY  = 0x01;
    public static final int MODE_CAPTURE_FRAME_ONLY = 0x02;

    public static final int METADATA_KEY_CD_TRACK_NUMBER = 0;
    public static final int METADATA_KEY_ALBUM           = 1;
    public static final int METADATA_KEY_ARTIST          = 2;
    public static final int METADATA_KEY_AUTHOR          = 3;
    public static final int METADATA_KEY_COMPOSER        = 4;
    public static final int METADATA_KEY_DATE            = 5;
    public static final int METADATA_KEY_GENRE           = 6;
    public static final int METADATA_KEY_TITLE           = 7;
    public static final int METADATA_KEY_YEAR            = 8;
    public static final int METADATA_KEY_DURATION        = 9;
    public static final int METADATA_KEY_NUM_TRACKS      = 10;
    public static final int METADATA_KEY_IS_DRM_CRIPPLED = 11;
    public static final int METADATA_KEY_CODEC           = 12;
    public static final int METADATA_KEY_RATING          = 13;
    public static final int METADATA_KEY_COMMENT         = 14;
    public static final int METADATA_KEY_COPYRIGHT       = 15;
    public static final int METADATA_KEY_BIT_RATE        = 16;
    public static final int METADATA_KEY_FRAME_RATE      = 17;
    public static final int METADATA_KEY_VIDEO_FORMAT    = 18;
    public static final int METADATA_KEY_VIDEO_HEIGHT    = 19;
    public static final int METADATA_KEY_VIDEO_WIDTH     = 20;
    public static final int METADATA_KEY_WRITER          = 21;
    public static final int METADATA_KEY_MIMETYPE        = 22;
    public static final int METADATA_KEY_DISCNUMBER      = 23;
    public static final int METADATA_KEY_ALBUMARTIST     = 24;
    // 可再往下擴充
}

使用時,設定資料來源後呼叫 captureFrame() 就能拿到代表幀,別忘了最後要 release()。

現代的替代方案

補充一點時事:上面這套「自己搬 libmedia_jni.so」的技巧屬於早期 Android 的產物,依賴特定 ABI 的 so 檔,在 64 位元與後續版本上很容易出問題。Android 4.0(API 14)起,MediaMetadataRetriever 已成為公開 API,直接呼叫即可;Android 4.4(API 19)之後又補上了 getScaledFrameAtTime(),可以一次取得指定尺寸的縮圖,省去自己縮放的功夫。新專案沒有必要再走 JNI 這條路,只有在維護老專案時才會碰到。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved