简体   繁体   English

来自Uri的bitmap.compress导致OutOfMemoryError

[英]bitmap.compress from Uri resulting in OutOfMemoryError

I am trying to save a bitmap which user selects into my own App path. 我正在尝试将用户选择的位图保存到我自己的App路径中。

Unfortunately, with very big images I get OutOfMemoryError error. 不幸的是,对于很大的图像,我得到OutOfMemoryError错误。

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? 有什么办法可以将Uri的任何大小的图像文件保存到文件中?

*I am not in a position to resize the image eg by using calculateInSampleSize method. *我无法调整图像的大小,例如,通过使用calculateInSampleSize方法。

Is there any way for me to save any image file of any size for an Uri to a file? 有什么办法可以将Uri的任何大小的图像文件保存到文件中?

Since it already is an image, just copy the bytes from the InputStream to the OutputStream : 由于它已经是图像,因此只需将字节从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();
    }
}

(adapted from this SO answer ) (改编自此SO答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM