-2

I am trying to fetch file from device storage and showing it in image view . Sometimes it is working perfectly fine, but sometimes not. Although bitmap is there but image view remains black.

Kindly suggest.

storage file Location

 file:/storage/emulated/0/Download/Full-hd-nature-wallpapers-free-download2.jpg

method which is returning bitmap

public static Bitmap convertToBitmap(File file) {

    URI uri = null;
    try {
          uri = file.toURI();            
       BitmapFactory.Options options = new BitmapFactory.Options();            
        options.inSampleSize = 1;            
        Bitmap bmp = BitmapFactory.decodeStream(uri.toURL().openStream(), new Rect(), options);

       //bmp.recycle();
        return bmp;

    } catch (Exception e) {
        return null;
    }//catch
}

setting image

      imageViewPatientImage.setImageBitmap(convertToBitmap(new File(mImagePath));
Community
  • 1
  • 1
Harneet Kaur
  • 4,487
  • 1
  • 16
  • 16

1 Answers1

0

Try this:

  Bitmap bitmap = getThumbnail(uri);
  showImage.setImageBitmap(bitmap);

Pass Bitmap for Optimization:

 public  Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
    InputStream input = getContext().getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither=true;//optional
    onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

    double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0;

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither=true;//optional
    bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
    input = getContext().getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    input.close();
    return bitmap;
}

private static int getPowerOfTwoForSampleRatio(double ratio){
    int k = Integer.highestOneBit((int)Math.floor(ratio));
    if(k==0) return 1;
    else return k;
}
Veeresh Charantimath
  • 4,641
  • 5
  • 27
  • 36