对于一个裸的RTSP URL,存放在播放列表上略显单调与枯燥。大家可以看到EasyPlayer在播放完视频后会保存一帧图片到列表上。
那么这个功能是如何做到的呢? 如果自己实现解码的话,比如使用ffmpeg解码,这种情况下,将视频帧解码,再编码成jpeg保存下来,应该不是什么难事。相信大多数播放器都是这样处理的。
H264格式的视频码流=>解码=>YUV格式的视频帧=>压缩=>jpeg=>保存到本地
但是如果我们用硬解码,很遗憾,安卓的硬解码并没有提供获取视频帧数据的功能,那又该如何实现呢? 有两种方法可以实现硬解码截屏
单独创建只为抓图用的软解码器并用上面的方法来抓图直接获取TextureView的内容并保存这里介绍下第二种方法。TextureView提供了一个getBitmap() 的方法,解释如下:
Returns a Bitmap rePResentation of the content of the associated surface texture.
该方法提供了当前TextureView的渲染内容,作为一个Bitbmap对象返回。这样我们可以将这个Bitmap压缩成jpeg、png等格式并保存下来。Bitmap提供了compress 方法可以直接压缩。下面为从TextureView获取并存储Bitmap对象的方法:
public void takePicture(final String path) { try { if (mWidth <= 0 || mHeight <= 0) { return; } Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); mSurfaceView.getBitmap(bitmap); saveBitmapInFile(path, bitmap); bitmap.recycle(); } catch (OutOfMemoryError error) { error.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } }下面是将Bitmap保存成JPEG的方法,这里,同时会将缩略图保存在安卓系统的相册中,以便调用系统的选取图片的方法可以访问到:
private void saveBitmapInFile(final String path, Bitmap bitmap) { FileOutputStream fos = null; try { fos = new FileOutputStream(path); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); if (mScanner == null) { MediaScannerConnection connection = new MediaScannerConnection(getContext(), new MediaScannerConnection.MediaScannerConnectionClient() { public void onMediaScannerConnected() { mScanner.scanFile(path, null /* mimeType */); } public void onScanCompleted(String path1, Uri uri) { if (path1.equals(path)) { mScanner.disconnect(); mScanner = null; } } }); try { connection.connect(); } catch (Exception e) { e.printStackTrace(); } mScanner = connection; } } catch (IOException e) { e.printStackTrace(); } catch (OutOfMemoryError error) { error.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }这里需要注意的是getBitmap函数的调用时机,
首先一定要在TextureView创建之后调用。即在onSurfaceTextureAvailable方法回掉之后才能调用,否则Texture尚未创建,该函数会返回null 。不仅如此,还需要在视频播放之后再调用。否则TextureView所展示的内容为空,因此您保存的快照可能是纯黑色的。新闻热点
疑难解答