如何从App中的URL下载图像

时间:2011-10-14 06:27:05

标签: android

我想知道如何从给定的网址下载图片并将其显示在ImageView 中。是否需要在permissions文件中提及manifest.xml

5 个答案:

答案 0 :(得分:6)

您需要将此permission设置为访问互联网

<uses-permission android:name="android.permission.INTERNET" />

你可以尝试这段代码。

String imageurl = "YOUR URL";
InputStream in = null;

try 
{
    Log.i("URL", imageurl);
    URL url = new URL(imageurl);
    URLConnection urlConn = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) urlConn;
    httpConn.connect();

    in = httpConn.getInputStream();
} 
catch (MalformedURLException e) 
{
    e.printStackTrace();
} 
catch (IOException e) 
{
    e.printStackTrace();
}
Bitmap bmpimg = BitmapFactory.decodeStream(in);
ImageView iv = "YOUR IMAGE VIEW";
iv.setImageBitmap(bmpimg);  

答案 1 :(得分:3)

使用背景线程获取图像,并在使用hanndler将图像设置在imageview中之后。

new Thread(){
     public void run() {
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(new URL("http://imageurl").openStream());
            Message msg = new Message();
            msg.obj = bitmap;
            imageHandler.sendMessage(msg);
         } catch (Exception e) {
            e.printStackTrace();
         } 
     }
 }.start();

我们在imgaeview中设置下载图像的处理程序代码。

Handler imageHandler = new Handler(){
    public void handleMessage(Message msg) {
        if(msg.obj!=null && msg.obj instanceof Bitmap){
            imageview.setBackgroundDrawable(new BitmapDrawable((Bitmap)msg.obj));
        }

    };
};

当然,您需要互联网许可。

<uses-permission android:name="android.permission.INTERNET" />

答案 2 :(得分:2)

您需要在Android清单文件中设置usage的{​​{1}}权限,并使用INTERNETjava.net.URL类到request网址。

答案 3 :(得分:0)

BitmapFactory - 类可以做到这一点。它可以从Bitmap创建InputStream - 对象,然后可以在ImageView中显示。

您应该知道的是,使用普通URLConnectionInputStream - 对象上获取URL并不总是与位图工厂一起使用。这里介绍了解决方法:Android: Bug with ThreadSafeClientConnManager downloading images

答案 4 :(得分:0)

看看这个:

选项A:

public static Bitmap getBitmap(String url) {
    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
        bis.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return bm;
}

选项B:

public Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        input.close();
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Jus在后台线程中运行该方法。