我使用的是安卓版本10,我已经开启了存储设备的读写权限名称: Poco F1
场景:我必须捕获当前布局的屏幕截图,并将其保存到internalStorage,然后向用户预览该图像。在这里,用户可以选择删除图像。
下面是我用来保存和删除的代码
保存截图:
//I will pass the bitmap here
fun saveBitmapToInternalStorage(bitmap: Bitmap?) {
bitmap?.let {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
saveBitmapToOlderDevice(it)
} else {
saveBitmapToNewerDevice(it)
}
}
}
//This method is to save image to newerdevice >= Q
@RequiresApi(Build.VERSION_CODES.Q)
private fun saveBitmapToNewerDevice(bitmap: Bitmap) {
val uri = generateUri()
context.contentResolver.openOutputStream(uri ?: return).use { outputStream ->
outputStream?.let {
writeBitmapToJpeg(bitmap, outputStream, uri.toString())
}
}
}
//This is to generate the URI.
@RequiresApi(Build.VERSION_CODES.Q)
private fun generateUri(): Uri? {
val dateFormat = getDateFormat()
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "${dateFormat}.jpg")
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures/${context.resources.getString(R.string.app_name)}")
}
return context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
)
}
// To save images to olderDevice
private fun saveBitmapToOlderDevice(bmp: Bitmap) {
val filename = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)?.absolutePath +
"/${context.resources.getString(R.string.app_name)}/${getDateFormat()}.jpg"
createDirectory(filename)
val outputStream = FileOutputStream(filename)
writeBitmapToJpeg(bmp, outputStream, filename)
}
//This method is to save the image to InternalStorage
private fun writeBitmapToJpeg(bmp: Bitmap, outputStream: OutputStream, imagePath: String) {
try {
val outputData = ByteArrayOutputStream()
bmp.compress(CompressFormat.JPEG, 100, outputData)
outputData.writeTo(outputStream)
outputStream.flush()
outputStream.close()
} catch (e: IOException) {
showBitmapWriteErrorMessage()
}
}在internalStorgae中存储图像时,我保存了路径,路径如下所示
/storage/emulated/0/Pictures/TGP AR/20211011142001.jpg和我将此路径传递到以下方法
要删除图像,请执行以下操作:
private fun deleteImage(imagePath: String) {
val file = File(imagePath)
file.delete()
}file.exists()返回true。file.delete()返回false。
我认为,可能有两种不同的方法来删除(>&
发布于 2021-10-23 04:51:23
您可以通过将您的方法修改为以下内容来删除镜像:
private fun deleteImage(imagePath: Uri) {
getContentResolver().delete(imagePath, null, null)
}然后传递在generateUri()中创建的Uri删除该文件。
https://stackoverflow.com/questions/69520306
复制相似问题