2016-05-12 65 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