Android 应用显示来自 URL 的图像

Android App Display Image From URL(Android 应用显示来自 URL 的图像)

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

问题描述

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

I'm looking for a very basic function. I'm trying to design an app and all I want it to do is load an image from a URL. I've found a few questions and websites, but they all seem to be older and dated, but what I think I'm having issues with is linking the code to activity main.xml for ImageView.

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

Any suggestions or links you have I would greatly appreciate, thank you.

推荐答案

这就是我如何在图像视图中显示来自 url 的图像
您必须从主线程以外的线程调用此代码

Here, this is how I display image from url in the image view
you have to call this code from thread other than main thread

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包围代码(我已经在这段代码中这样做了)

Be careful don't forget to surround the code with try catch(I have already done that in this code)

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

or you can use webview to load image from url

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

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

if you are trying to load image from the assets folder url will start like this "file:///android_asset/yourimage.jpg"
else normal internet url like this "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"

希望这对你有用祝你好运

hope this works for you Good Luck

这篇关于Android 应用显示来自 URL 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Android 应用显示来自 URL 的图像

基础教程推荐