简体   繁体   中英

Android: Error when saving file to SD Card

I've been trying to save a JPG image to the SD Card in order to then scale it down and display it in an ImageView (due to the original size causing an Out of memory error).

Here's the method I use to save the file:

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

Then here is when I call on that method and then try to load a scaled down image into memory and put it into the 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);

However, when I try to run this, I get the LogCat message saying:

"java.io.FileNotFoundException: /mnt/sdcard/myImage.jpg: open failed : EACCES (Permission denied)"

I've also made sure to add

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

to the manifest.

Does anyone have any ideas?

Edit: The error occurs at line 107 and 72, meaning that it occurs when I try to save the image.

Bump: Anyone? Would really appreciate some suggestions.

Problem solved! Turns out all I needed to change was the size of the byte buffer in the saveImage method. It was at 1024 but after upping it to 8192 it's working fine!

Thanks for everyone elses suggestions.

use the following:

String  path = Environment.getExternalStorageDirectory()
                                .toString() + File.separator + "myImage.jpg";
OutputStream output = new FileOutputStream (path,true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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