/**
* 将图片在相册显示
*/
private fun updatePhotoAlbum(bitmap: Bitmap, file: File) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val values = ContentValues()
values.put(MediaStore.Images.Media.DATA, file.absolutePath)
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
//将项直接插入到MediaStore 将自动扫描它们
val uri: Uri? = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
} else {
MediaScannerConnection.scanFile(this, arrayOf(file.absolutePath), arrayOf("image/png")) { _, _ ->
object : Thread() {
override fun run() {
super.run()
saveBitmap(bitmap)
}
}.start()
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
fun saveBitmap(bitmap: Bitmap) {
val values = ContentValues()
values.put(MediaStore.Images.Media.DESCRIPTION, "This is an image")
values.put(MediaStore.Images.Media.DISPLAY_NAME, "Image.png")
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png")
values.put(MediaStore.Images.Media.TITLE, System.currentTimeMillis().toString() + ".png")
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Camera")
val external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val resolver: ContentResolver = contentResolver
val insertUri: Uri? = resolver.insert(external, values)
var os: OutputStream? = null
if (insertUri != null) {
try {
os = resolver.openOutputStream(insertUri)
bitmap.compress(Bitmap.CompressFormat.PNG, 90, os)
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
os?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
网友评论