【问题标题】:How to convert bitmap to Uri using MediaColumns#IS_PENDING?如何使用 MediaColumns#IS_PENDING 将位图转换为 Uri?
【发布时间】:2020-01-09 05:33:06
【问题描述】:

我正在使用以下代码将位图转换为 Uri:

fun convertBitmapToUri(context: Context, bitmap: Bitmap): Uri {
    val bytes = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(context.contentResolver, bitmap, "Title", null)
    return Uri.parse(path)
}

此代码运行良好。但是,在将 sdk 版本更新为 29 后,insertImage 方法已被弃用。而当我查看doc时,我看到了这样的说法:

此方法在 API 级别 29 中已弃用。应使用 MediaColumns#IS_PENDING 执行图像插入,它提供了对生命周期的更丰富的控制。

那么,如何使用 MediaColumns#IS_PENDING 将位图转换为 Uri?

【问题讨论】:

标签: android kotlin mediastore


【解决方案1】:

试试下面的sn-p:

此方法可以帮助您从位图中获取 Uri 而不会消耗一些额外的内存。

 private fun convertToUri(mBitmap: Bitmap): Uri? {
    var uri: Uri? = null
    try {
        val options: BitmapFactory.Options = BitmapFactory.Options()
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 100, 100)

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false
        val newBitmap = Bitmap.createScaledBitmap(
            mBitmap, 200, 200,
            true
        )
        val file = File(
            this.filesDir, "Image"
                    + Random().nextInt() + ".jpeg"
        )
        val out = this.openFileOutput(
            file.name,
            Context.MODE_WORLD_READABLE
        )
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
        out.flush()
        out.close()
        //get absolute path
        val realPath = file.absolutePath
        val f = File(realPath)
        uri = Uri.fromFile(f)

    } catch (e: Exception) {

    }
    return uri
}

fun calculateInSampleSize(
    options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int
): Int {
    // Raw height and width of image
    val height = options.outHeight
    val width = options.outWidth
    var inSampleSize = 1

    if (height > reqHeight || width > reqWidth) {

        val halfHeight = height / 2
        val halfWidth = width / 2

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
            && (halfWidth / inSampleSize) >= reqWidth
        ) {
            inSampleSize *= 2
        }
    }

    return inSampleSize
}

【讨论】:

    【解决方案2】:

    这是将 bimpa 转换为 URI 的代码

    private fun saveImage(myBitmap : Bitmap) : String {
    
        val bytes = ByteArrayOutputStream()
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    
        val folder = File(Environment.getExternalStorageDirectory().absolutePath + "/" + ".yourFolder")
        // have the object build the directory structure, if needed.
        if (!folder .exists()) {
            folder .mkdirs()
        }
    
        try {
            val f = File(folder , "image_name.jpg")
            f.createNewFile()
            val fo = FileOutputStream(f)
            fo.write(bytes.toByteArray())
            MediaScannerConnection.scanFile(this, arrayOf(f.path), arrayOf("image/*"), { path, uri -> 
                val _uri = uri // Here is your URI from bitmap
                val _path = path // In case if you want path of that bitmp in storage
            })
            fo.close()
    
            return f.absolutePath
        } catch (e1 : IOException) {
            e1.printStackTrace()
        }
    
        return ""
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      相关资源
      最近更新 更多