1

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);
    }
Husein Behboudi Rad
  • 5,434
  • 11
  • 57
  • 115

1 Answers1

0

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();
}
WonderSoftwares
  • 2,800
  • 1
  • 15
  • 21
  • Your answer is correct, the problem was that I do not check the path exist or not. but the getParent() returns String. I create a new file for parent directory and check it. Please edit your answer so that I can accept it – Husein Behboudi Rad Jun 19 '15 at 09:23