java - 如何在关闭应用程序之前保存和恢复位图
问题描述
我想为应用程序的用户制作可替换的个人背景。当他们更改图片时,我无法在关闭应用程序之前保存它。我尝试共享首选项,但不适用于位图。如何在关闭应用程序之前保存和恢复位图?
解决方案
//use this method to save your bitmap, call this method when you have bitmap
private void saveBitmap(Bitmap pBitmap){
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir("folderName", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "fileName.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
pBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
String filePath = file.getAbsolutePath();
//save this path in shared preference to use in future.
} catch (Exception e) {
Log.e("SAVE_IMAGE", e.getMessage(), e);
}
}
使用此方法从您保存的文件路径中获取位图
private void getBitmapFromPath(String pFilePath) {
try {
File f = new File(pFilePath);
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
//use this bitmap as you want
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
用于保存和检索文件路径
//This for saving file path
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("FILE_PATH_KEY", filePath).apply();
//this for getting saved file path
String filePath = PreferenceManager.getDefaultSharedPreferences(context).getString("FILE_PATH_KEY", "path not retrieved successfully!");
推荐阅读
- vba - 根据excel列表将文件从源文件路径复制到目标文件路径
- glsl - 在 GLSL 顶点着色器中,您可以访问索引缓冲区中顶点的索引,而不仅仅是顶点缓冲区吗?
- mysql - 检查第 2 列的值是否包含在 sql 的第 1 列中
- javascript - Lodash - 如何计算数组中的出现次数
- python - Python 3.8 shared_memory resource_tracker 在应用程序关闭时产生意外警告
- c# - c#Settngs“按钮”提示使用默认打印机,将设置保存到ini文件
- flutter - 我的颤振程序中有一些错误
- javascript - 通过 node.js 从字符串中删除 /
- c++ - OOP 中的单个成员指针
- ios - 当我尝试从 Firebase 检索数据库信息时,为什么 SwiftUI 会显示错误?