Android 将图片保存到系统相册 兼容Android Q以上
class BitmapSave {
fun save(context:Context, input: InputStream, file:File, fileName: String = "shareQChanger.jpg"){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
saveBitmap2SelfDirectory(input,file,fileName)
val values = ContentValues()
values.put(MediaStore.Images.Media.DATA, "${file.absolutePath}/$fileName")
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
intent.data = uri
context.sendBroadcast(intent)
} else {
val values = ContentValues()
values.put(MediaStore.Images.Media.DESCRIPTION, "This is an qr image")
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.Media.TITLE, "Image.jpg")
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/")
val external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val resolver: ContentResolver = context.contentResolver
val insertUri = resolver.insert(external, values)
val inputStream = BufferedInputStream(input)
var os: OutputStream? = null
try {
if (insertUri != null) {
os = resolver.openOutputStream(insertUri)
}
if (os != null) {
val buffer = ByteArray(1024 * 4)
var len: Int
while (inputStream.read(buffer).also { len = it } != -1) {
os.write(buffer, 0, len)
}
os.flush()
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
os?.close()
inputStream.close()
if (insertUri != null) {
resolver.update(insertUri,values,null,null)
}
}
}
}
//保存图片至app私有目录
private fun saveBitmap2SelfDirectory(input: InputStream, fileDirectory: File, fileName: String) {
var file: File? = null
file = File(fileDirectory, fileName)
val inputStream = BufferedInputStream(input)
try {
val fos = FileOutputStream(file)
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
val buffer = ByteArray(1024 * 4)
var len: Int
while (inputStream.read(buffer).also { len = it } != -1) {
fos.write(buffer, 0, len)
}
fos.flush()
fos.close()
inputStream.close()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
使用
val file = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
BitmapSave().save(baseContext,resources.openRawResource(R.mipmap.share),file)