无法从外部存储中删除位图



我似乎无法从本地存储中删除图片。我想发生的是:删除旧图片,添加同名新图片。 当我更改图片名称时,将其作为新图片加载没有问题。但是当我不更改它的名字时,它会显示旧图片。 我尝试了context.deleteFile(文件名(。file.exists 在删除后返回 false,但图片仍然存在。 具有覆盖功能的解决方案可能会有所帮助。 我在清单中还具有外部存储权限。 谢谢!

删除:

void deleteOldPicture(String filename, Context context){
File file = new ImageSaver(context).setFileName(filename).setDirectoryName("images").createFile();
file.delete();
}

创建文件

File createFile() {
File directory;
if(external){
directory = getAlbumStorageDir(directoryName);
}
else {
directory = context.getDir(directoryName, Context.MODE_PRIVATE);
}
return new File(directory, fileName);
}
private File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e("ImageSaver", "Directory not created");
}
return file;
}

保存文件:

private String saveFileInSD(String name, ImageView image){
String filename = name+parentId+".png";
Log.e("Filename is", filename);
new ImageSaver(getApplicationContext()).setFileName(filename).setDirectoryName("images").save(((BitmapDrawable) image.getDrawable()).getBitmap());
return filename;
}

将此库添加到您的 Gradle 中,它将帮助您稍微清理一下代码:

implementation 'org.apache.commons:commons-io:1.3.2'

执行以下操作以保存图片:

//Compress the Bitmap
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//save Bitmap to file and get it form preview activity and especially to avoid TransactionTooLargeException
File imageFile = new File(getExternalCacheDir(), "image.png");
try {
FileOutputStream imageFileStream = new FileOutputStream(imageFile);
IOUtils.copyLarge(new ByteArrayInputStream(stream.toByteArray()), imageFileStream);
IOUtils.closeQuietly(imageFileStream);
} catch (Exception e) {
e.printStackTrace();
}

要获取保存的位图的路径,只需使用以下方法:

imageFile.getAbsolutePath()

最新更新