Create a Bitmap/Drawable from file path

173,689

Solution 1

Create bitmap from file path:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);

If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.

I think you are giving the wrong file path. :) Hope this helps.

Solution 2

It works for me:

File imgFile = new  File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    //Drawable d = new BitmapDrawable(getResources(), myBitmap);
    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    myImage.setImageBitmap(myBitmap);

}

Edit:

If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:

String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new  File(sdcardPath);

Solution 3

here is a solution:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Solution 4

Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

Solution 5

static ArrayList< Drawable>  d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
  myDrawable =  Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
  d.add(myDrawable);
}
Share:
173,689
Nari Kim Shin
Author by

Nari Kim Shin

Android @Twitter

Updated on April 04, 2021

Comments

  • Nari Kim Shin
    Nari Kim Shin about 3 years

    I'm trying to create a Bitmap or Drawable from existing file path.

    String path = intent.getStringExtra("FilePath");
    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inPreferredConfig = Bitmap.Config.ARGB_8888;
    
    mImg.setImageBitmap(BitmapFactory.decodeFile(path));
    // mImg.setImageBitmap(BitmapFactory.decodeFile(path, option));
    // mImg.setImageDrawable(Drawable.createFromPath(path));
    mImg.setVisibility(View.VISIBLE);
    mText.setText(path);
    

    But setImageBitmap(), setImageDrawable() doesn't show an image from the path. I've printed path with mText and it looks like : /storage/sdcard0/DCIM/100LGDSC/CAM00001.jpg

    What am i doing wrong? Anyone can help me?