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)
分类:
kotlin
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】