首页 > 解决方案 > 'createVideoThumbnail(String, Int): 位图?已弃用。在 Java 中已弃用

问题描述

当我遇到这个问题时,我查看了这个答案,但即使使用了这段代码,android studio 仍然显示这个警告

我使用的代码

val bitmapThumbnail = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ThumbnailUtils.createVideoThumbnail(
                    File(it.data?.getStringExtra("videoPath").toString()),
                    Size(120, 120),
                    null)
            } else {
                ThumbnailUtils
                    .createVideoThumbnail(
                        it.data?.getStringExtra("videoPath").toString(),
                        MediaStore.Video.Thumbnails.MINI_KIND
                    )
            }

标签: javaandroidandroid-studiokotlin

解决方案


问题是旧功能指的是新功能。看一下源代码:

@Deprecated
public static @Nullable Bitmap createVideoThumbnail(@NonNull String filePath, int kind) {
    try {
        return createVideoThumbnail(new File(filePath), convertKind(kind), null);
    } catch (IOException e) {
        Log.w(TAG, e);
        return null;
    }
}

在旧资源中翻找了一下,我找到了它并对其进行了一些调整:

    private const val TARGET_SIZE_MICRO_THUMBNAIL = 96
    private const val MINI_KIND = 1
    private const val MICRO_KIND = 3
    private fun createVideoThumbnail(filePath: String?, kind: Int): Bitmap? {
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
        try {
            retriever.setDataSource(filePath)
            bitmap = retriever.getFrameAtTime(-1)
        } catch (ex: IllegalArgumentException) {
            // Assume this is a corrupt video file
        } catch (ex: RuntimeException) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release()
            } catch (ex: RuntimeException) {
                // Ignore failures while cleaning up.
            }
        }
        if (bitmap == null) return null
        if (kind == MINI_KIND) {
            // Scale down the bitmap if it's too large.
            val width = bitmap.width
            val height = bitmap.height
            val max = width.coerceAtLeast(height)
            if (max > 512) {
                val scale = 512f / max
                val w = (scale * width).roundToInt()
                val h = (scale * height).roundToInt()
                bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true)
            }
        } else if (kind == MICRO_KIND) {
            bitmap = extractThumbnail(
                bitmap,
                TARGET_SIZE_MICRO_THUMBNAIL,
                TARGET_SIZE_MICRO_THUMBNAIL,
                OPTIONS_RECYCLE_INPUT
            )
        }
        return bitmap
    }

推荐阅读