萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 使用 MediaMetadataRetriever 擷取影片幀並轉為 Bitmap 儲存

核心類別:MediaMetadataRetriever

API Level 10+ 提供,可從媒體來源擷取中繼資料與特定時間點的幀畫面。

完整實作 (MainActivity.java)

package cn.testmediametadataretriever;

import java.io.File;
import java.io.FileOutputStream;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new ClickListenerImpl());
    }

    private class ClickListenerImpl implements OnClickListener {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.button) getBitmapsFromVideo();
        }
    }

    public void getBitmapsFromVideo() {
        String dataPath = Environment.getExternalStorageDirectory() + "/testVideo.mp4";
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(dataPath);

        // 取得影片長度 (毫秒)
        String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        int seconds = Integer.valueOf(time) / 1000;

        // 每秒擷取一幀 (單位:微秒 us)
        for (int i = 1; i <= seconds; i++) {
            Bitmap bitmap = retriever.getFrameAtTime(i * 1000 * 1000, 
                    MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            if (bitmap == null) continue;

            String path = Environment.getExternalStorageDirectory() + File.separator + i + ".jpg";
            try (FileOutputStream fos = new FileOutputStream(path)) {
                bitmap.compress(CompressFormat.JPEG, 80, fos);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        retriever.release(); // 釋放資源
    }
}

版面配置 (res/layout/main.xml)

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="獲取視頻的幀圖片"
        android:layout_centerInParent="true" />

</RelativeLayout>

關鍵點總結

  • getFrameAtTime(timeUs, option) 第一參數單位為微秒 (1秒 = 1,000,000 us)。
  • OPTION_CLOSEST_SYNC 取最接近的關鍵幀,速度較快;OPTION_CLOSEST 精確但較慢。
  • 執行緒中操作耗時較久,建議放入背景執行緒 (RxJava/Coroutines/AsyncTask) 避免 ANR。
  • 需權限:READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE。
copyright © 萬盛學電腦網 all rights reserved