当开始做这个时候的,我用的是MediaMetadataRetriever,然后发现他会出现getFrameAtTime: videoFrame is a NULL pointer,就获取不到图片。后来将MediaMetadataRetriever换成了FFmpegMediaMetadataRetriever就解决了这个问题,如下。

一、先导入依赖

    implementation 'com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.14'

二、我将其封装成了两个方法,就是根据指定路径去将视频转化为图片

		//因为我自己的一些需求,我添加了一个picturepath,这个方法里的三个参数可以根据自己的需要,将其去掉,变为两个参数
     public static String bitmaptoFile(String path, String picturepath, String name) {
        Bitmap bitmap = getBitmap(path);
        if(bitmap==null){
            getBitmap(path);
        }
        //将图片的名字以.jpg结尾
        File f = new File(picturepath +"/"+ name + ".jpg");
        if (f.exists()) {
            f.delete();
        }

        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
            //这里可以选择转化的类型的,有三种JPEG、PNG、WEBP,根据自己的选择,然后第二个参数则是转化的质量,100是最好的即无损
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            Log.e("TAG", "bitmap转file出错 , "+e.toString());
            return null;
        }
        return f.getAbsolutePath();
    }

    public static Bitmap getBitmap(String path) {
        Bitmap bitmap = null;
        FFmpegMediaMetadataRetriever mediaMetadataRetriever = new FFmpegMediaMetadataRetriever();
        File file = new File(path);//实例化File对象,文件路径为/storage/sdcard/Movies/music1.mp4
        try {
            if (file.exists()) {
                mediaMetadataRetriever.setDataSource(file.getAbsolutePath());//设置数据源为该文件对象指定的绝对路径
                bitmap = mediaMetadataRetriever.getFrameAtTime(1000000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST);//获得视频的Bitmap对象
            }
        } catch (IllegalArgumentException e) {
            Log.e("转bitmap出错" , e.toString(), e);
        }
        mediaMetadataRetriever.release();
        return bitmap;
    }

三、然后在需要用的地方进行使用就可以了。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐