来自 URL 的 Android 可绘制图像 [英] Android Drawable Images from URL

查看:36
本文介绍了来自 URL 的 Android 可绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码将图像加载为可绘制对象形成 URL.

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);

}

此代码完全按预期工作,但似乎存在兼容性问题.在 1.5 版中,当我给它一个 URL 时,它会抛出一个 FileNotFoundException.在 2.2 中,给定完全相同的 URL,它工作正常.以下 URL 是我提供此函数的示例输入.

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

如何以与 URL 全面兼容的方式加载图像?

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 {

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

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

    return BitmapFactory.decodeStream(input);
}

添加用户代理也很重要,因为如果不存在,googlebooks 将拒绝访问

It was also important to add in the user agent, as googlebooks denies access if it is absent

这篇关于来自 URL 的 Android 可绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆