在 Android Q 中从 Sdcard 生成缩略图

Generate Thumbnail From Sdcard in Android Q

我正在使用以下方法生成缩略图(在 android 10 中已弃用)

thumbnail_bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);

像这样获取异常

java.io.IOException: Failed to create thumbnail

谢谢。

您的实施存在一些问题。

第一个是 createVideoThumbnail 已更改为:

public static Bitmap createVideoThumbnail (String filePath, int kind)

public static Bitmap createVideoThumbnail (File file, Size size, CancellationSignal signal)


第二种是检索 path 并尝试将其转换为 Uri:

的方式
String path = getExternalFilesDir(Environment.DIRECTORY_MOVIES) .getAbsolutePath()+ "/" + new SimpleDateFormat("yyyyMM_dd-HHmmss").format(new Date()) + "_compress.mp4";

Uri fileUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(path));

您应该改为使用 ContentValues ContentResolver 创建一个 Uri,然后写入 Uri 并在完成后将其插入,如下所示:

ContentValues valuesvideos = new ContentValues();
valuesvideos.put(MediaStore.Images.Media.RELATIVE_PATH, "Movies/");
valuesvideos.put(MediaStore.Images.Media.TITLE, fileName);
valuesvideos.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
valuesvideos.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
valuesvideos.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesvideos.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
valuesvideos.put(MediaStore.Images.Media.IS_PENDING, 1); 
ContentResolver resolver = getContentResolver(); 

Uri collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); 

Size mSize = new Size(96,96);
CancellationSignal ca = new CancellationSignal(); 
Bitmap bitmapThumbnail = getContentResolver().loadThumbnail(collection, mSize, ca);

Uri uriSavedThumb = resolver.insert(collection, valuesvideos);

这是从存储中生成视频缩略图的解决方案。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {

            thumbnail_bitmap = createThumbnail(RecordPitchActivity.this, path);

        } else {
            thumbnail_bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
        }
public static Bitmap createThumbnail(Activity activity, String path) {
        MediaMetadataRetriever mediaMetadataRetriever = null;
        Bitmap bitmap = null;
        try {
            mediaMetadataRetriever = new MediaMetadataRetriever();
            mediaMetadataRetriever.setDataSource(activity, Uri.parse(path));
            bitmap = mediaMetadataRetriever.getFrameAtTime(1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mediaMetadataRetriever != null) {
                mediaMetadataRetriever.release();
            }
        }
        return bitmap;
    }