Android 应用程序显示来自 URL 的图像

标签 android url imageview

我正在寻找一个非常基本的功能。我正在尝试设计一个应用程序,我想让它做的就是从 URL 加载图像。 我发现了一些问题和网站,但它们似乎都比较陈旧和过时,但我认为我遇到的问题是将代码链接到 ImageView 的 Activity main.xml。

如果您有任何建议或链接,我将不胜感激,谢谢。

最佳答案

这就是我在 ImageView 中显示来自 url 的图像的方式
你必须从主线程以外的线程调用此代码

ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
        URL url = new URL("Your URL");
        //try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
        HttpGet httpRequest = null;

        httpRequest = new HttpGet(url.toURI());

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient
                .execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();

        Bitmap bitmap = BitmapFactory.decodeStream(input);

        img.setImageBitmap(bitmap);

    } catch (Exception ex) {

    }

注意不要忘记用try catch包围代码(我已经在这段代码中这样做了)

或者你可以使用 webview 从 url 加载图像

WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("Your Url");

如果您尝试从 Assets 文件夹加载图像,url 将像这样开始 “文件:///android_asset/yourimage.jpg”
否则像这样的正常互联网网址 "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg "

希望这对你有用 祝你好运

关于Android 应用程序显示来自 URL 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867278/

相关文章:

url - URL 的整个第一部分怎么称呼?

android - 为什么 ImageView 中可绘制对象的宽度/高度错误?

android - 如何使用 FrameLayout 使 Imageview 在屏幕上居中? (用java代码)

android - 我想编写一个 ImageView 先缓慢旋转然后逐渐增加旋转速度的程序

java - 如何检查Android手机是否支持TEE?

android - 付款创建错误paypal sdk android

java - 从java中的URL读取UTF-8编码的XML

android - 如何触发 Google Play 商店的自动更新机制?

android - 为什么我不能使用 getContentResolver.. 删除?

rest - 我可以安全地在 URL 查询字符串参数中添加 $(美元符号)前缀吗?