Save bitmap to android default pictures directory

1.5k views Asked by At

I use below code to save bitmap image (captured from layout) to android default picture directory. It seems that the saved image is corrupt because Gallery can not open this.

When I save the bitmap in another location the gallery can open it. but it is not opening when I save it to the android default directory.

   public void saveToGallery() {
        String path = Environment.getExternalStorageDirectory().toString()
                + "/Pictures/Keshavarzi/" + "screenshot-" + System.currentTimeMillis() + ".png";

        ViewGroup v = (ViewGroup) findViewById(R.id.lyt_main_report_activity);
        v.setDrawingCacheEnabled(true);
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false);



        OutputStream out = null;
        File imageFile = new File(path);

        try {
            out = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

            } catch (Exception exc) {
            }

        }


        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Title");
        values.put(MediaStore.Images.Media.DESCRIPTION, "Description");
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, path);

        getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);


        MHToast.showToast(getString(R.string.saved_in_gallery), Toast.LENGTH_LONG);
    }
1

There are 1 answers

1
WonderSoftwares On BEST ANSWER

try this, check if your save directory is exists or create directory first then save bitmap,

String path = Environment.getExternalStorageDirectory().toString()
            + "/Pictures/Keshavarzi/" + "screenshot-" + 

System.currentTimeMillis() + ".png";
File imageFile = new File(path);
if(!imageFile.getParentFile().exists()){
      imageFile.getParentFile().mkDirs();
}