2016-11-23 129 views
1

需要從路徑中獲取圖像。我嘗試了一切,但似乎沒有得到圖像。

我的兩個圖像路徑:
Android從路徑中獲取圖像(圖庫,圖片等)

/storage/emulated/0/DCIM/Camera/20161025_081413.jpg 
content://media/external/images/media/4828 

如何設置我的形象從這些路徑?
我正在使用ImageView來顯示我的圖像。

我的代碼:

File imgFile = new File("/storage/emulated/0/DCIM/Camera/20161025_081413.jpg"); 
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 
holder.myimage.setImageBitmap(myBitmap); 

在此先感謝

+0

你收到的一些錯誤,是文件存在於這條道路?檢查此:http://stackoverflow.com/questions/4181774/show-image-view-from-file-path –

+0

我沒有得到任何錯誤。路徑是正確的。我沒有得到圖像。不知道,如果我設置正確的方式 –

+0

確保您有閱讀權限:<使用權限android:name =「android.permission.READ_EXTERNAL_STORAGE」/>,也請確保文件不是很大 –

回答

0

我發現我的問題。我正在使用Android SDK 23.

來自Android文檔。
如果設備運行的是Android 6.0或更高版本,並且您的應用的目標SDK爲23或更高:應用必須列出清單中的權限,並且它必須在應用運行時請求所需的每個危險權限。用戶可以授予或拒絕每個權限,並且即使用戶拒絕權限請求,應用也可以繼續以有限的功能運行。 https://developer.android.com/training/permissions/requesting.html

希望這有助於別人

+0

今天剛碰到這個! – RexSplode

1

定期,你可以只寫BitmapFactory.decodeBitmap(....)等,但該文件可以是巨大的,你可以得到的OutOfMemoryError很快,特別是,如果你在一行中解碼幾次。因此,您需要在將圖像設置爲查看前壓縮圖像,以免內存不足。這是做到這一點的正確方法。

File f = new File(path); 
if(file.exists()){ 
Bitmap myBitmap = ImageHelper.getCompressedBitmap(photoView.getMaxWidth(), photoView.getMaxHeight(), f); 
        photoView.setImageBitmap(myBitmap); 
} 

//////////////

/** 
    * Compresses the file to make a bitmap of size, passed in arguments 
    * @param width width you want your bitmap to have 
    * @param height hight you want your bitmap to have. 
    * @param f file with image 
    * @return bitmap object of sizes, passed in arguments 
    */ 
    public static Bitmap getCompressedBitmap(int width, int height, File f) { 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(f.getAbsolutePath(), options); 

     options.inSampleSize = calculateInSampleSize(options, width, height); 
     options.inJustDecodeBounds = false; 

     return BitmapFactory.decodeFile(f.getAbsolutePath(), options); 
    } 

/////////////////

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     int inSampleSize = 1; 

     if (height > reqHeight || width > reqWidth) { 

      final int halfHeight = height/2; 
      final int halfWidth = width/2; 

      // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
      // height and width larger than the requested height and width. 
      while ((halfHeight/inSampleSize) >= reqHeight 
        && (halfWidth/inSampleSize) >= reqWidth) { 
       inSampleSize *= 2; 
      } 
     } 

     return inSampleSize; 
    } 
+0

嗨,謝謝你的例子。我嘗試過,但我仍然有同樣的問題。沒有圖像 –

+0

您計算或使用了哪種樣本量?你要求哪個寬度和高度? – greenapps

+0

我的問題是Android SDK 23有它的權限。當我解決這個問題時,我使用了你的壓縮代碼,它完美的工作。謝謝。你爲我節省了很多工作。希望我能給你更多的讚揚。 –