bitmap.compress 来自 Uri,导致 OutOfMemoryError

bitmap.compress from Uri resulting in OutOfMemoryError

我正在尝试将用户选择的位图保存到我自己的应用程序路径中。

不幸的是,对于非常大的图像,我会遇到 OutOfMemoryError 错误。

我正在使用以下代码:

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));
}

有什么方法可以将 Uri 的任何大小的图像文件保存到文件中吗?

*我无法调整图像的大小,例如通过使用 calculateInSampleSize 方法。

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

因为它已经是一个图像,只需将字节从 InputStream 复制到 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();
    }
}

(改编自this SO answer