首页 > 解决方案 > 如何在关闭应用程序之前保存和恢复位图

问题描述

我想为应用程序的用户制作可替换的个人背景。当他们更改图片时,我无法在关闭应用程序之前保存它。我尝试共享首选项,但不适用于位图。如何在关闭应用程序之前保存和恢复位图?

标签: javaandroidandroid-studio

解决方案


//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!");

推荐阅读