Señ*_*cis 29 url android image drawable
我目前正在使用以下代码将图像作为可绘制对象加载到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);
}
Run Code Online (Sandbox Code Playgroud)
此代码完全按照需要工作,但似乎存在兼容性问题.在1.5版本中,它会FileNotFoundException
在我给它一个URL时抛出一个.在2.2中,给定完全相同的URL,它工作正常.以下URL是我提供此功能的示例输入.
http://bks6.books.google.com/books?id=aH7BPTrwNXUC&printsec=frontcover&img=1&zoom=5&edge=curl&sig=ACfU3U2aQRnAX2o2ny2xFC1GmVn22almpg
Run Code Online (Sandbox Code Playgroud)
如何以一种从URL兼容的方式加载图像?
Fel*_*ipe 47
位图不是Drawable.如果你真的需要Drawable这样做:
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(Resources.getSystem(), x);
}
Run Code Online (Sandbox Code Playgroud)
(我使用了/sf/answers/169145231/中的提示)
Señ*_*cis 15
自己解决了.我使用以下代码将其作为位图加载.
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);
}
Run Code Online (Sandbox Code Playgroud)
添加到用户代理中也很重要,因为如果不存在,googlebooks会拒绝访问
我不确定,但我认为Drawable.createFromStream()更适用于本地文件而不是下载的InputStreams.尝试使用BitmapFactory.decodeStream()
,然后将返回的Bitmap包装在BitmapDrawable中.