2014-03-24 86 views
0

我想要做類似於imageView.setImageResource(R.drawable.myimage);的操作,但我不想提供來自應用資源的圖像,我想指向一個文件(/sdcard/.../image.jpg)。Android從文件路徑設置背景

有沒有辦法做到這一點,不涉及加載位圖,然後將位圖設置爲imageview?

感謝

+0

您可以使用'BitmapFactory.decodeFile(String filePath)'。 –

+0

@HosseinMobasher這創建了一個位圖,我正在尋找一種方法,不這樣做來節省一些資源 – Thomas

回答

3

您可以從SD卡更新的背景如下...

String pathName = Environment.getExternalStorageDirectory().getPath() + "/folder/" + "image.jpg"; 
Bitmap bitmap = BitmapFactory.decodeFile(pathName); 
imageView.setImageBitmap(bitmap); 
+1

爲什麼你需要前兩行?你可以做'BitmapFactory.decodeFile(路徑);'然後'新的BitmapDrawable(位圖)' - 你不需要這些資源。 –

+0

@AleksG ...你說得對。我已經更新了我的答案。 –

+0

謝謝,但我問是否有方法不是加載位圖。 (由於內存不足錯誤) – Thomas

1

嘗試這種方式

public Bitmap ImgBitFromFile(String file_name) { 

    File imgFile = new File(file_name); 

    if (imgFile.exists()) { 

     Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 

     return myBitmap; 
    } 
    return null; 
} 

而像使用:

img.setImageBitmap(ImgBitFromFile(File_Path)); 

,做不要忘記添加閱讀您的manifest.xml文件的權限。

+1

請勿在android應用程序中使用'System.out.println'。改用'Log.d'。 –