兼容android Q存图片到相册

fun Context.saveBitmap2Galley(bitmap: Bitmap, dir: String = "", name: String): Boolean {

    val isSuccessed: Boolean
    val fos: OutputStream?
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/$dir")
        val imageUri =
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        fos = imageUri?.let { contentResolver.openOutputStream(it) }
    } else {
        val imageDir = Environment.getExternalStoragePublicDirectory("newMedia/qcodes")
        if (!imageDir.exists()) {
            imageDir.mkdirs()
        }
        val file = File(imageDir, name)

        fos = FileOutputStream(file)
    }
    isSuccessed = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
    fos?.flush()
    fos?.close()

    return isSuccessed
}

 需要请求权限

你可能感兴趣的:(android)