2012-08-06 19 views
26

我有一個URI像它具有圖像如何從Android中的URL獲取位圖?

file:///mnt/............... 

如何使用URI來獲得圖像,但它返回null,請告訴我,我錯了。

Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath()); 
Bitmap bitmap = BitmapFactory.decodeFile(uri.toString()); 

回答

79

這是一個簡單的一條線的方式來做到這一點:所以你想從一個文件中的位圖

try { 
     URL url = new URL("http://...."); 
     Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
    } catch(IOException e) { 
     System.out.println(e); 
    } 
+2

這不是一句話,因爲創建你的url對象應該被try-catch包圍。 – portfoliobuilder 2015-03-17 22:14:09

+0

這個想法是獲得位圖的一種方式,因爲您已經定義了一個url。 – brthornbury 2015-04-19 04:36:38

+4

'url.openConnection()。getInputStream()'可以被替換爲簡單的'url.openStream()' – 2015-12-15 21:14:03

16

這應該做的伎倆:

public static Bitmap getBitmapFromURL(String src) { 
    try { 
     URL url = new URL(src); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     Bitmap myBitmap = BitmapFactory.decodeStream(input); 
     return myBitmap; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} // Author: silentnuke 

不要忘記添加Internet權限在您的清單。

+0

怎麼回合我的網址有https連接? – 2017-04-10 07:39:04

1

好嗎?標題說URL。無論如何,當你從Android的外部存儲獲取文件時,你絕對不應該使用直接路徑。相反,調用getExternalStorageDirectory()像這樣:

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE); 
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile); 

getExternalStorageDirectory()爲您提供了路徑的SD卡。 您還需要在Manifest中聲明WRITE_EXTERNAL_STORAGE權限。