如何将位图保存到android中的应用程序文件夹

Mar*_*ner 4 java android android-file

我有一个位图,我想将其保存到应用程序文件夹中。我尝试使用这些代码:

 ContextWrapper contextWrapper = new ContextWrapper(context.getApplicationContext());
 File directory = contextWrapper.getDir("tabs", Context.MODE_PRIVATE);
 if (!directory.exists())
     directory.mkdir();
     String fname = "Image.jpg";
     File file = new File(directory, fname);
     FileOutputStream fos = null;
     try {
         fos = new FileOutputStream(file);
         bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
         fos.close();
     } catch (Exception e) {
            Log.e("SAVE_IMAGE", e.getMessage(), e);
     }
Run Code Online (Sandbox Code Playgroud)

现在,我有两个问题。

  1. 为什么会显示此警告以及如何修复它?

“File.mkdir()”的结果被忽略

  1. 在应用程序文件夹中创建了目录“app_tabs”,但未保存位图,并且该文件夹中没有照片。如何保存该位图?

截屏

小智 5

你可以这样做:

try {
     FileOutputStream fileOutputStream = context.openFileOutput("Your File Name", Context.MODE_PRIVATE);
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
     fileOutputStream.close();
 } catch (Exception e) {
     e.printStackTrace();
 }
Run Code Online (Sandbox Code Playgroud)

它将您的位图保存在应用程序文件夹的“文件”目录中。