可直接使用的Bitmap保存至手机图库(Kotlin 版)适配A
2020-12-11 本文已影响0人
飞指
fun saveToPicDir(context: Context, bitmap: Bitmap): String {
var result = ""
val imageFileType = when (bitmap.hasAlpha()) {
true -> "png"
false -> "jpeg"
}
val bitmapFormat = when (bitmap.hasAlpha()) {
true -> Bitmap.CompressFormat.PNG
false -> Bitmap.CompressFormat.JPEG
}
val fileName =
"${System.currentTimeMillis()}.$imageFileType"
ContentValues().apply {
put(MediaStore.Images.Media.TITLE, fileName)
put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
put(MediaStore.Images.Media.DESCRIPTION, "描述文件")
if (Build.VERSION.SDK_INT >= 29) {
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/${MissBearConst.MB_DIR_SAVE}")
}
put(MediaStore.Images.Media.MIME_TYPE, "image/$imageFileType")
val uri =
context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, this)
var outputStream: OutputStream? = null
try {
outputStream = context.contentResolver.openOutputStream(uri!!)
bitmap.compress(bitmapFormat, 100, outputStream)
uri.path?.let { result = it }
} catch (e: java.lang.Exception) {
e.printStackTrace()
} finally {
outputStream?.let {
it.flush()
it.close()
}
}
if (Build.VERSION.SDK_INT >= 26) {
if (uri != null) {
sendBroadcastToPic(context, uri)
}
}
}
return result
}
/**
* 适配Android 8.0 出现保存之后不通知图库更新的问题
*/
private fun sendBroadcastToPic(context: Context, imageUri: Uri) {
var path = ""
val query = context.contentResolver.query(
imageUri,
arrayOf(MediaStore.Images.ImageColumns.DATA),
null,
null,
null
)
if (query == null) {
path = imageUri.path!!
} else {
query.moveToFirst()
val name: Int = query.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
path = query.getString(name)
query.close()
}
MediaScannerConnection.scanFile(context, arrayOf(path), null, null);
}