class SavePictureToAlbumUtils { /** * 将图片文件保存到系统相册 */ fun saveImgFileToAlbum(mContext: Context, imageFilePath: File) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { saveBitmapToAlbumAfterQ(mContext, imageFilePath) } else { saveBitmapToAlbumBeforeQ(mContext, imageFilePath) } } fun saveBitmapToAlbumAfterQ(mContext: Context, imageFilePath: File) { var uri: Uri? = null try { val resolver = mContext.contentResolver // 获取外部存储目录的URI val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI // 构造ContentValues对象并设置数据 val values = ContentValues() values.put(MediaStore.Images.Media.DISPLAY_NAME, imageFilePath.name) // 设置显示名称 values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") // 设置MIME类型 // 调用insert()方法将图片保存到相册 uri = resolver.insert(collection, values) } catch (e: Exception) { } // 判断uri是否有效 if (uri == null || !imageFilePath.exists()) { toast("保存失败") } else { // 复制图片到相册 try { val inputStream: InputStream = FileInputStream(imageFilePath) val outputStream = mContext.contentResolver.openOutputStream(uri) val buffer = ByteArray(4 * 1024) var bytesRead: Int while (inputStream.read(buffer).also { bytesRead = it } != -1) { outputStream!!.write(buffer, 0, bytesRead) } outputStream!!.flush() outputStream!!.close() inputStream.close() log("SaveImage", "Successfully saved the image!") toast("已保存到手机相册") } catch (e: Exception) { toast("保存失败") } } } fun saveBitmapToAlbumBeforeQ(mContext: Context, imageFilePath: File) { try { MediaStore.Images.Media.insertImage( mContext.contentResolver, imageFilePath.absolutePath, imageFilePath.name, null ); MediaScannerConnection.scanFile( mContext, arrayOf(imageFilePath.path), arrayOf("image/jpeg"), null ) toast("已保存到手机相册") } catch (e: Exception) { toast("保存失败") } } }
android 图片保存到系统相册,兼容android10
于 2024-01-20 16:57:04 首次发布