从视频流读取帧图像保存到本地
在进行全景视频播放器开发的时候,遇到在不同的播放设备上颜色不一致的情况,故进行Debug。
首先想到的是,在不同的硬件平台上解码得到的视频帧数据是否有问题,故写了一个测试方法用于从视频流数据读取一帧保存到本地文件夹中。
下面开始建立这样一个工程
新建New Project,名字为GetPicFromVideoStream
首先在AndroidManifest.xml加入权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
然后进入layout.xml,加入一个Button,点击获得截图
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Get Picture"/>
然后再MainActivity中写入如下代码:
public void getPicture(){
//设置视频路径
String path = Environment.getExternalStorageDirectory() + "/demo.mp4";
Log.v("Tony", "Path:"+ path);
//将路径实例化为一个文件对象
File file = new File(path);
//判断对象是否存在,不存在的话给出Toast提示
if(file.exists()){
//提供统一的接口用于从一个输入媒体中取得帧和元数据
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(path);
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("Tony", "Time:"+ time);
int seconds = Integer.valueOf(time) / 1000;
seconds = 10;
for (int i = 1; i < seconds; i++){
Bitmap bitmap = retriever.getFrameAtTime(i*1000*1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
String pathPic = Environment.getExternalStorageDirectory()+File.separator + i + ".jpg";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pathPic);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
Log.v("Tony", "Picture Got");
fos.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}else {
Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
}
}
在onCreate中加入
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getPicture();
}
});
以下是Log输出
04-07 21:07:37.831 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Path:/storage/emulated/0/demo.mp4
04-07 21:07:37.841 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Time:173248
04-07 21:07:38.891 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:39.871 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:40.851 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:41.781 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:42.651 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:43.601 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:44.511 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:45.431 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got
04-07 21:07:46.391 9786-9786/me.syzhang.www.getpicfromvideostream V/Tony: Picture Got