Android 保存图片到相册 亲测有效

private fun saveToGallery(bitmap: Bitmap){
        // 首先保存图片
        var file: File? = null
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        val root =
            File(Environment.getExternalStorageDirectory(), packageName)
        val dir = File(root, "images")
        if (dir.mkdirs() || dir.isDirectory) {
            file = File(dir, fileName)
        }
        try {
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
            MessageUtils.showToast("保存成功")
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        //其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(
                this.contentResolver,
                file!!.absolutePath, fileName, null
            )
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        // 通知图库更新
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            MediaScannerConnection.scanFile(
                this,
                arrayOf(file!!.absolutePath),
                null
            ) { _, uri ->
                val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                mediaScanIntent.data = uri
                sendBroadcast(mediaScanIntent)
            }
        } else {
            val relationDir = file!!.parent
            val file1 = File(relationDir)
            sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_MOUNTED,
                    Uri.fromFile(file1.absoluteFile)
                )
            )
        }
    }

测试机型:红米10 ,华为P30,OPPOR17

你可能感兴趣的:(Android 保存图片到相册 亲测有效)