【问题标题】:bitmap.compress from Uri resulting in OutOfMemoryError来自 Uri 的 bitmap.compress 导致 OutOfMemoryError
【发布时间】:2015-07-25 21:22:22
【问题描述】:

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

不幸的是,对于非常大的图像,我会遇到 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 方法。

【问题讨论】:

    标签: android bitmap out-of-memory


    【解决方案1】:

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

    既然已经是图片,只需将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

    【讨论】:

    • 这对我不起作用...没有错误,只是没有文件!我的 Uri (filePath) 指向一个本地文件。有什么想法吗?
    • @user1148358:使用调试器单步调试您的代码。如果代码将大量字节写入您想要的File,那么显然该文件存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多