Search code examples
androidbitmapstorage

How to save image in external storage from bitmap in android


I am using ACTION_IMAGE_CAPTURE to capture image using camera. It works fine, But the problem is that image is showing in imageview after clicking but can not saved in external or internal storage. Here is my code for saving image in external storage.

Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/DashBoard/");
        file.mkdirs();
        ticket = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DashBoard/Ticket.jpg";
        file4 = new File(file, ticket);
        try {
            FileOutputStream out = new FileOutputStream(file4);
            bitmap.compress(Bitmap.CompressFormat.JPEG , 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ivTicket.setImageBitmap(bitmap);

Any solution ?


Solution

  • Try This:

    private void SaveImage(Bitmap finalBitmap) {
     String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
     myDir.mkdirs();
     Random generator = new Random();
     int n = 10000;
     n = generator.nextInt(n);
     String fname = "Image-"+ n +".jpg";
     File file = new File (myDir, fname);
     if (file.exists ()) file.delete (); 
     try {
       FileOutputStream out = new FileOutputStream(file);
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.flush();
       out.close();
    
    } catch (Exception e) {
       e.printStackTrace();
    }
    }
    

    and add this in manifest

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    

    another example here

    UPDATE instead of Environment.getExternalStorageDirectory() you can use your storage location as API level 30 and above Storage-policy is changed.