首页 > 解决方案 > 如何在videoView android中截取当前视频帧的屏幕截图?

问题描述

我正在使用视频视图播放媒体,我想截取当前帧的屏幕截图。我找到了一些解决方案,其中包括使用 mediaMetaDataRetriever,但该方法太慢并且在许多情况下都表现不佳。我不能在纹理视图上使用媒体播放器来捕获我知道这种方法的视图,因为我的应用程序中默认需要媒体控件。有什么方法可以加快这个过程吗?我的代码:

 public Bitmap getBitmapVideoView(){
        MediaMetadataRetriever mediaMetadataRetriever;
        mediaMetadataRetriever = new MediaMetadataRetriever();
        try {
            int currentPosition =videoView.getCurrentPosition();
            mediaMetadataRetriever.setDataSource(getVideoURL(),new HashMap<String, String>());
            Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(currentPosition*1000);
            if (bitmap != null) {
//                Canvas canvas = new Canvas(bitmap);
//                textureview.draw(canvas);
                return bitmap;
            }
            else{
                return null;
            }
        }
        catch (Exception e){
            Log.i("Errorrr",e.getMessage());
            return null;
        }
        finally {
            try {
                mediaMetadataRetriever.release();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }

方法:

Bitmap bitmap = Screenshot.INSTANCE.with((MainActivity)activity).setView(findViewById(R.id.relative)).setQuality(Quality.HIGH).getScreenshot();
                    LayoutInflater inflater = getLayoutInflater();
                    Toast toastShot = null;
                    View layout = inflater.inflate(R.layout.layout, (ViewGroup) findViewById(R.id.screen));
                    ImageView image = (ImageView) layout.findViewById(R.id.shot_image);
                    image.setImageBitmap(bitmap);
                    toastShot = new Toast(getApplicationContext());
                    toastShot.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                    toastShot.setDuration(Toast.LENGTH_LONG);
                    toastShot.setView(layout);
                    toastShot.show();

标签: androidmediaandroid-videoview

解决方案


要截屏,您可以使用此库

implementation 'com.github.MindorksOpenSource:screenshot:v0.0.1'

而要截取屏幕截图,只需在按钮单击或任何其他事件上调用此函数

 var b = Screenshot.with(activity!!).setView(rl_imageText).setQuality(Quality.HIGH).getScreenshot()

注意:rl_imageText = 这是我正在截取的 xml 相对布局的 ID。

它将为您提供屏幕截图的位图,并将其保存到存储中或获取路径使用下面提到的功能

private fun getImageUriFromBitmap(context: Context, bitmap: Bitmap): Uri {
    val bytes = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(context.contentResolver, bitmap,"Title",null)
    return Uri.parse(path.toString())
}

注意:如果它不起作用,请提及,以便我为您提供其他解决方案。


推荐阅读