Search code examples
androidbitmapandroid-sdcardandroid-galleryandroid-external-storage

Reading Bitmap from the gallery and writing it into the sd card fails


I want to copy a Bitmap from the gallery to a path on the sd card.

This function works well for the picture which is taken from the camera:

public void saveBitmap(Bitmap bitMap, Uri avatarUri) throws Exception{
        File file = new File(avatarUri.toString());
//        if (file.exists ()) file.delete ();
        try {
            OutputStream fOut = new FileOutputStream(file);
            if (bitMap.compress(Bitmap.CompressFormat.PNG, 100, fOut)) {
                fOut.flush();
                fOut.close();
            } else {
                Log.d("123", "compress file");
            }
        } catch (Exception e) {
            Log.d("123", "File not found file");
        }
}

But when i select an image from the gallery by using:

void getImageFromGallery(Intent data) throws FileNotFoundException {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        avatarBitmap = bitmap;
    }

And use the saveBitmap() method to save this choosen image, it catches a File not found exception.
This method generates a folder and returns a URI for the saveBitmap()method.

 public Uri generateAvatarImageUri(String patientName) {
        Date date = new Date(0);
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
        String filename =  sdf.format(date) + patientName;
        return Uri.fromFile(new File(getExternalStorageDirectory(), avatarFolderPath+filename+".jpg"));
    }
}

Any help?


Solution

  • Finally i got the reason, it's because the file path issue.

    this is what i used:

    Uri uri = ....;
    path = uri.toString();
    

    Which leads to a prefix file:/// was added into the path string like:

    file:///storage/...png
    

    Hope can help some others.