2013-04-04 32 views

回答

34

如果此圖片設置爲的形象圖與File你說的是File對象,我會嘗試:

File file = .... 
Uri uri = Uri.fromFile(file); 
imageView.setImageURI(uri); 
+0

烏里imageUri = Uri.parse( ImagePath的); imageView.setImageURI(imageUri); ...這適用於除小米Mi4之外的所有設備,任何想法爲何如此。 – Avijeet 2016-01-09 11:36:08

+0

這不適用於我的設備中的大圖像(例如:1.5MB或2MB)。任何方式來壓縮它(我只是想顯示縮略圖)。 – 2016-10-09 01:39:42

+0

它沒有設置正確的圖像尺寸,Lakshay Sharma的答案是關於圖像尺寸的完美結合 – 2017-05-18 09:46:19

8

你可以給一個嘗試這種代碼:

imageView.setImageBitmap(BitmapFactory.decodeFile(yourFilePath)); 

BitmapFactory將指定圖像文件解碼成位圖對象,然後您將設置到imageView對象中。

+2

這是最簡單的方法。顯然,如果你只是返回文件而不是路徑。使用'file.getPath()'而不是'yourFilePath' – mr0mr 2013-04-04 15:05:35

7

從一個文件中設置的圖像,你需要這樣做:

File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg"); //your image file path 
mImage = (ImageView) findViewById(R.id.imageView1); 
mImage.setImageBitmap(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250)); 

decodeSampledBitmapFromFile

public static Bitmap decodeSampledBitmapFromFile(String path, 
     int reqWidth, int reqHeight) { // BEST QUALITY MATCH 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, options); 

    // Calculate inSampleSize 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     options.inPreferredConfig = Bitmap.Config.RGB_565; 
     int inSampleSize = 1; 

     if (height > reqHeight) { 
      inSampleSize = Math.round((float)height/(float)reqHeight); 
     } 

     int expectedWidth = width/inSampleSize; 

     if (expectedWidth > reqWidth) { 
      //if(Math.round((float)width/(float)reqWidth) > inSampleSize) // If bigger SampSize.. 
      inSampleSize = Math.round((float)width/(float)reqWidth); 
     } 


    options.inSampleSize = inSampleSize; 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 

    return BitmapFactory.decodeFile(path, options); 
    } 

您可以用數字(在這種情況下,500和250)改打位圖的質量爲ImageView

1

從文件加載圖像:

Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture); 

假設你pathToPicture是正確的,你可以那麼這個位圖圖像添加到ImageView

ImageView imageView = (ImageView) getActivity().findViewById(R.id.imageView); 
imageView.setImageBitmap(BitmapFactory.decodeFile(pathToPicture));