Android intercepts video frames and converts them to the Bitmap example
- 2020-05-10 18:52:49
- OfStack
MainActivity is as follows:
main. xml as follows:
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;
/**
* Demo describe :
* using MediaMetadataRetriever Capture the video by time
* And converted into Bitmap Stored in SDCard
*
* Pay special attention to :
* getFrameAtTime() Methods the first 1 Is in microseconds (us)
*
*/
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) {
switch (v.getId()) {
case R.id.button:
getBitmapsFromVideo();
default:
break;
}
}
}
public void getBitmapsFromVideo() {
String dataPath = Environment.getExternalStorageDirectory()+ "/testVideo.mp4";
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(dataPath);
// Get the length of the video ( In milliseconds )
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
// Get the length of the video ( The unit is in seconds )
int seconds = Integer.valueOf(time) / 1000;
// For each 1 The second time bitmap Such as the first 1 seconds , The first 2 seconds
for (int i = 1; i <= seconds; i++) {
Bitmap bitmap = retriever.getFrameAtTime(i*1000*1000,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
String path = Environment.getExternalStorageDirectory()+ File.separator + i + ".jpg";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
bitmap.compress(CompressFormat.JPEG, 80, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
main. xml as follows:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=" Gets the frame image of the video "
android:layout_centerInParent="true"
/>
</RelativeLayout>