1

I am trying to save a bitmap which user selects into my own App path.

Unfortunately, with very big images I get OutOfMemoryError error.

I am using the following code:

private String loadImage (Uri filePath) {
    File fOut = new File(getFilesDir(),"own.jpg");

    inStream = getContentResolver().openInputStream(filePath);
    selectedImage = BitmapFactory.decodeStream(inStream);

    selectedImage.compress(CompressFormat.JPEG, 100, new FileOutputStream(fOut));
}

Is there any way for me to save any image file of any size for an Uri to a file?

*I am not in a position to resize the image e.g. by using calculateInSampleSize method.

1 Answers1

0

Is there any way for me to save any image file of any size for an Uri to a file?

Since it already is an image, just copy the bytes from the InputStream to the OutputStream:

private void copyInputStreamToFile( InputStream in, File file ) {
    try {
        FileOutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[8192];
        int len;

        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }

        out.flush();
        out.getFD().sync();
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

(adapted from this SO answer)

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • This does not work for me ... no errors, just no file! My Uri (filePath) is pointing to a local file. Any thoughts? –  Jul 26 '15 at 12:44
  • @user1148358: Step through your code using a debugger. If the code is writing lots of bytes out to your desired `File`, then clearly the file exists. – CommonsWare Jul 26 '15 at 12:49