Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read an Image/file from External storage Android

I'm trying to load an image from external storage. I set the permissions, I tried different ways, but none of them works.

BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    Bitmap bitmap = BitmapFactory.decodeFile(file.toString()); 

    tv.setImageBitmap(bitmap);

and this one,

FileInputStream streamIn = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(streamIn); 

    tv.setImageBitmap(bitmap);
        streamIn.close();
like image 946
Ramin Anushir Avatar asked Apr 10 '13 06:04

Ramin Anushir


People also ask

How do I access external files on Android 11?

Users can see which apps have the READ_EXTERNAL_STORAGE permission in system settings. On the Settings > Privacy > Permission manager > Files and media page, each app that has the permission is listed under Allowed for all files. If your app targets Android 11, keep in mind that this access to "all files" is read-only.


2 Answers

If i have file abc.jpg on the sdcard then:

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

and to get bitmap.

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

or

Bitmap bitmap1 = BitmapFactory.decodeFile(photoPath);

to avoide out of memory error I suggest you use the below code...

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);

To avoid above issue you can use Picasso (A powerful image downloading and caching library for Android)

Documentation

How To?

Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
like image 62
Dhaval Parmar Avatar answered Sep 28 '22 05:09

Dhaval Parmar


File sdCard = Environment.getExternalStorageDirectory();

File directory = new File (sdCard.getAbsolutePath() + "/Pictures");

File file = new File(directory, "image_name.jpg"); //or any other format supported

FileInputStream streamIn = new FileInputStream(file);

Bitmap bitmap = BitmapFactory.decodeStream(streamIn); //This gets the image

streamIn.close();
like image 45
Shiv Avatar answered Sep 28 '22 04:09

Shiv