Read an Image/file from External storage Android

前端 未结 5 1893
借酒劲吻你
借酒劲吻你 2020-12-03 12:32

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 =          


        
相关标签:
5条回答
  • 2020-12-03 12:41
    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();
    
    0 讨论(0)
  • 2020-12-03 12:41

    Get the path of the image from your folder as below. And then decode the file as a bitmap.

       File file= new File(android.os.Environment.getExternalStorageDirectory(),"Your folder");
       Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath())
    
    0 讨论(0)
  • 2020-12-03 13:02

    There is a function called

    createFromPath(String)
    

    in the Drawable class. So the statement

    String path="/storage/..<just type in the path>";
    Drawable.createFromPath(path);
    

    will return a drawable object

    0 讨论(0)
  • 2020-12-03 13:03

    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);
    
    0 讨论(0)
  • 2020-12-03 13:03

    If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

    BitmapFactory.Options options = new BitmapFactory.Options();
    
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    
    Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
    selected_photo.setImageBitmap(bitmap);
    
    0 讨论(0)
提交回复
热议问题