Search code examples
androidandroid-storage

Android get image in secondary storage


I am trying to get an image from phone's secondary storage.

public void downloadImage(View v) {

    Bitmap myImage = GetImageBitmapFromUrl();
    String path = System.getenv("SECONDARY_STORAGE") + "/";
    OutputStream out = null;
    try 
    {
        File file = new File(path, "nameImage.jpg");
        out = new FileOutputStream(file);
        myImage.compress(Bitmap.CompressFormat.JPEG, 85, out);
        out.flush();
        out.close();
     } 
    catch (Exception e)
    {    
    }
}

When I run with debug why I get this error and it didn't receive the file also.

Error at:

myImage.compress(Bitmap.CompressFormat.JPEG, 85, out);

In the manifests file:

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

Solution

  • String photoPath = Environment.getExternalStorageDirectory()+"/photo.jpg";
    

    and get bitmap by using code below. The photo.jpg is the the name of the image you want to read.

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
    

    You can also use picasso image library

    Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
    Picasso.with(context).load(new File(...)).into(imageView3);