小编P.J*_*uni的帖子

Android 8 保存位图时图像名称和类型错误

我很高兴将位图保存为 PNG 或 JPG(两者都不起作用),但似乎使用内容值无法按预期工作。

  1. 文件名不正确。
  2. 文件类型不正确。

我缺少什么?适用于 Android 10,但不适用于 Android 8

fun Bitmap.save(context: Context) {
    val contentResolver = context.contentResolver

    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, "test.png")
        put(MediaStore.MediaColumns.TITLE, "test")
        put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
            put(MediaStore.MediaColumns.IS_PENDING, 1)
        }
    }

    val contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val uri = contentResolver.insert(contentUri, contentValues)
    if (uri != null) {
        try {
            contentResolver.openFileDescriptor(uri, "w", null)?.use {
                if (it.fileDescriptor != null) {
                    with(FileOutputStream(it.fileDescriptor)) {
                        compress(
                            Bitmap.CompressFormat.PNG,
                            DEFAULT_IMAGE_QUALITY,
                            this
                        )
                        flush()
                        close()
                    }
                }
            }
        } catch …
Run Code Online (Sandbox Code Playgroud)

android bitmap kotlin

3
推荐指数
1
解决办法
1178
查看次数

Unit 和 { } 的区别

我想我不明白Unit和之间的区别是什么{},例如在乐趣中使用回调时。

fun x(
    callback: () -> Unit = {} // fine
)

fun x(
    callback: () -> Unit = Unit // not fine
)
Run Code Online (Sandbox Code Playgroud)

kotlin

0
推荐指数
1
解决办法
62
查看次数

标签 统计

kotlin ×2

android ×1

bitmap ×1