Search code examples
javaandroidandroid-file

How to Save bitmap to app folder in android


I have a bitmap that I want to save it to the app folder. I try with these codes:

 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);
     }

Now, I have two problems.

  1. Why this warning show and how to fix it?

Result of 'File.mkdir()' is ignored

  1. Directory "app_tabs" was created in the application folder, But not saved bitmap and There is no photo in the folder. How do I save this bitmap?

ScreenShot


Solution

  • You can just do this:

    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();
     }
    

    It saves your bitmap in the "files" directory in app folder.