从URL Android的可绘制图片 [英] Android Drawable Images from URL
问题描述
我是presently使用下面这段code加载的图像,绘制对象形成一个网址。
绘制对象drawable_from_url(URL字符串,字符串src_name)
抛出java.net.MalformedURLException,产生java.io.IOException {
返回Drawable.createFromStream(((java.io.InputStream中的)新的java.net.URL(URL).getContent()),src_name);
}
这code工程完全按照想要的,但似乎与它的兼容性问题。在1.5版本,它抛出一个 FileNotFoundException异常
时,我给它一个网址。在2.2,考虑到完全相同的网址,它工作正常。下面的网址是一个示例输入我给这个函数。
我将如何加载图像的方式,全线兼容,从一个网址?
解决它自己。我用下面的code加载它作为一个位图。
位图drawable_from_url(字符串URL)抛出java.net.MalformedURLException,产生java.io.IOException {
位图X;
HttpURLConnection的连接=(HttpURLConnection类)新的网址(URL).openConnection();
connection.setRequestProperty(用户代理,Mozilla的/ 4.0);
connection.connect();
输入的InputStream = connection.getInputStream();
X = BitmapFactory.de codeStream(输入);
返回X;
}
这是同样重要的是增加了用户代理,如googlebooks拒绝访问,如果它不存在
I am presently using the following piece of code to load in images as drawable objects form a URL.
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);
}
This code works exactly as wanted, but there appears to be compatibility problems with it. In version 1.5, it throws a FileNotFoundException
when I give it a URL. In 2.2, given the exact same URL, it works fine. The following URL is a sample input I am giving this function.
http://bks6.books.google.com/books?id=aH7BPTrwNXUC&printsec=frontcover&img=1&zoom=5&edge=curl&sig=ACfU3U2aQRnAX2o2ny2xFC1GmVn22almpg
How would I load in images in a way that is compatible across the board from a URL?
Solved it myself. I loaded it in as a bitmap using the following code.
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
It was also important to add in the user agent, as googlebooks denies access if it is absent
这篇关于从URL Android的可绘制图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!