2010-07-30 112 views
23

我目前使用下面的一段代碼將圖像加載爲可繪製對象形成一個URL。來自URL的Android可繪製圖像

Drawable drawable_from_url(String url, String src_name) 
throws java.net.MalformedURLException, java.io.IOException { 
     return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name); 

} 

此代碼的工作原理與想要的完全相同,但似乎存在兼容性問題。在版本1.5中,當我給它一個URL時它會拋出FileNotFoundException。在2.2中,給定完全相同的URL,它工作正常。下面的URL是我給這個函數的示例輸入。

http://bks6.books.google.com/books?id=aH7BPTrwNXUC&printsec=frontcover&img=1&zoom=5&edge=curl&sig=ACfU3U2aQRnAX2o2ny2xFC1GmVn22almpg 

我該如何加載圖像以便通過URL從一個URL兼容?

回答

12

自己解決。我使用下面的代碼作爲位圖加載它。

Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException { 

    HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection(); 
    connection.setRequestProperty("User-agent","Mozilla/4.0"); 

    connection.connect(); 
    InputStream input = connection.getInputStream(); 

    return BitmapFactory.decodeStream(input); 
} 

同樣重要的是在用戶代理添加,如Google圖書拒絕訪問,如果它不存在

5

我不知道,但我認爲Drawable.createFromStream()更旨在與本地文件,而不是下載InputStreams使用。嘗試使用BitmapFactory.decodeStream(),然後將返回的位圖封裝在BitmapDrawable中。

+0

我似乎記得之前遇到過這個問題;我當時在1.5。 – I82Much 2010-07-31 04:04:57

41

位圖是不是可繪製。如果你真的需要一個可繪製做到這一點:

public static Drawable drawableFromUrl(String url) throws IOException { 
    Bitmap x; 

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 
    connection.connect(); 
    InputStream input = connection.getInputStream(); 

    x = BitmapFactory.decodeStream(input); 
    return new BitmapDrawable(x); 
} 

(我用https://stackoverflow.com/a/2416360/450148發現了尖)

+0

很好的答案,但請注意,構造函數已被棄用。使用BitmapDrawable(資源,位圖)確保drawable已正確設置其目標密度 – avalancha 2015-11-11 08:21:28

+0

請編輯並修復它! – 2015-11-12 00:50:36

1

下面的代碼對我的作品:

Matrix Mat = new Matrix(); 

Bitmap Source = BitmapFactory.decodeFile("ItemImagePath"); 

Bitmap Destination = Bitmap.createScaledBitmap(Source, 320, 320, true); 

Source = Bitmap.createBitmap(Destination, 0, 0, Destination.getWidth(), Destination.getHeight(),Mat, true); 

ItemImageView.setImageBitmap(Source); 
+1

這使我的應用程序崩潰 – Christopher 2013-01-15 10:42:26

+0

@Christopher - 崩潰如何 - 在主線程上聯網? – 2014-09-17 21:58:42

1

您可以使用com.androidquery。 AndroidQuery很簡單地做到這一點。例如:

AQuery aq = new AQuery(this); 
aq.id(view).image("http://yourserver/yourimage.png", true, true, 300, new BitmapAjaxCallback() { 
     @Override 
     public void callback(String url, ImageView imageView, Bitmap bitmap, AjaxStatus status) { 
      Drawable drawable = new BitmapDrawable(getResources(), bm); 
     } 
    }); 

如果使用BitmapAjaxCallback你會得到訪問,你可以包裝爲BitmapDrawable的位圖。

+0

問題不在於此,請再閱讀! – 2013-10-11 18:51:59

+0

請幫助我,我不明白爲什麼我的答案不適用於這裏... – 2013-10-14 11:16:43

+0

該人要求某種方式來創建從網址drawable,你是一個正在做的下面,無法得到** drawable **;相反,你傳遞一個視圖,並且圖書館將它從url下載的圖像設置在它上面。那麼如何才能將它視爲問題的答案呢? – 2013-10-22 06:42:21