1

我一直在尝试将 JPG 图像保存到 SD 卡,以便将其缩小并显示在 ImageView 中(由于原始大小导致内存不足错误)。

这是我用来保存文件的方法:

public void saveImage(String src) throws IOException{
        URL url = new URL (src); 
        InputStream input = url.openStream(); 
        try {     
            File storagePath = Environment.getExternalStorageDirectory();
            OutputStream output = new FileOutputStream (new File(storagePath, "myImage.jpg"));     
            try {         
                byte[] buffer = new byte[1024];         
                int bytesRead = 0;         
                while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                        output.write(buffer, 0, bytesRead);         
                }     
            }  
            finally {         
                output.close();     
            } 
        } 

        finally {     
            input.close(); 
        }
    }

然后是当我调用该方法然后尝试将按比例缩小的图像加载到内存中并将其放入 ImageView 中时:

try {
            saveImage(src);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 20;



        File storagePath = Environment.getExternalStorageDirectory();
        File file = new File(storagePath, "myImage.jpg");

        Bitmap scaledDownImage = BitmapFactory.decodeFile(file.getAbsolutePath(), options);


        imageFrame1.setImageBitmap(scaledDownImage);

但是,当我尝试运行它时,我收到 LogCat 消息说:

“java.io.FileNotFoundException:/mnt/sdcard/myImage.jpg:打开失败:EACCES(权限被拒绝)”

我也确保添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

到清单。

有没有人有任何想法?

编辑:错误发生在第 107 行和第 72 行,这意味着它发生在我尝试保存图像时。

砰:有人吗?真的很感激一些建议。

4

2 回答 2

0

问题解决了!原来我需要改变的是 saveImage 方法中字节缓冲区的大小。它在 1024,但在将其提高到 8192 后,它工作正常!

谢谢大家的建议。

于 2012-12-09T10:48:49.853 回答
-1

使用以下内容:

String  path = Environment.getExternalStorageDirectory()
                                .toString() + File.separator + "myImage.jpg";
OutputStream output = new FileOutputStream (path,true);
于 2012-12-08T21:49:22.107 回答