Android 将图片保存到系统相册 兼容Android Q以上
作者:互联网
class BitmapSave { fun save(context:Context, inputStream: InputStream, file:File, fileName: String = "shareQChanger.jpg"){ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { saveBitmap2SelfDirectory(inputStream,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) 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() } } } //保存图片至app私有目录 private fun saveBitmap2SelfDirectory(inputStream: InputStream, fileDirectory: File, fileName: String) { var file: File? = null file = File(fileDirectory, fileName) 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) } inputStream.close() fos.flush() fos.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)
标签:相册,val,Media,兼容,values,file,Images,Android,MediaStore 来源: https://www.cnblogs.com/javaktolin/p/16309050.html