有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓“创建视频缩略图(字符串,Int):位图?”不推荐使用。在Java中已弃用

当我发现这个问题时,我研究了这个answer,但是即使使用了这个代码,安卓 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
                    )
            }

共 (1) 个答案

  1. # 1 楼答案

    问题是旧函数指的是新函数。看看源代码:

    @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
        }