2016-05-12 62 views
-2

我试图从设备存储中获取文件并在图像视图中显示它。有时它工作得很好,但有时候不行。尽管位图存在,但图像视图仍为黑色。未在imageView中设置位图随机问题

请提出建议。

存储文件位置

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

方法,其返回位图

公共静态位图convertToBitmap(文件文件){

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 
} 

设定图像

 imageViewPatientImage.setImageBitmap(convertToBitmap(new File(mImagePath)); 
+0

请发表您的代码。 –

+0

发布一些日志,因此可以提供帮助。 – Dhrupal

回答

0

试试这个:

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

通行证位图进行优化:

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; 
} 
+0

欲了解更多信息http://stackoverflow.com/questions/3879992/get-bitmap-from-an-uri-android –

+0

我试过但徒劳。同样的问题。有时它是开放的形象,但有时不是:( – Androiduser