下载图像的ImageView的在Android [英] Download image for imageview on Android

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

问题描述

我已经看到了这个问题:机器人如何下载一个1MB的图像文件,并设置为ImageView的
它并没有解决我的问题,因为它只是说明如何显示后位图的 您已经拥有了它。

我想从一个URL下载的图像将它用在Android设备上的ImageView的显示。我不知道如何做到这一点。

我四处张望了一下在互联网上,这是code我到目前为止有:

 公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    //设置本地图像
    ImageView的形象=(ImageView的)findViewById(R.id.test_image);
    image.setImageResource(R.drawable.test2);

    // prepare下载图片
    URL网址;
    在的InputStream;

    //的BufferedInputStream BUF;
    尝试 {
        URL =新的URL(http://i.imgur.com/CQzlM.jpg);
        在= url.openStream();

        OUT =新的BufferedOutputStream(新的FileOutputStream(testImage.jpg));
        INT I;

         而((ⅰ= in.read())!=  -  1){
             out.write(ⅰ);
         }
         out.close();
         附寄();

        BUF =新的BufferedInputStream(中);
        位图BMAP = BitmapFactory.de codeStream(BUF);
        image.setImageBitmap(BMAP);
        如果(在!= NULL){
        附寄();
        }
        如果(BUF!= NULL){
        buf.close();
        }
    }赶上(例外五){
        Log.e(读取文件错误,e.toString());
    }
}
 

解决方案

在code可能会工作,alltough你下载你的形象在你的主线程。这意味着,当它超过5秒下载,你会psented与著名的ANR对话框$ P $,和您的应用程序会崩溃...

您应该下载你的形象在后台线程,并发布结果返回给你的主线程。回到主线程,你可以下载的图像更新ImageView的。

下面是一个例子:

 包nl.entreco.stackoverflow;

进口java.io.BufferedInputStream中;
进口java.io.BufferedOutputStream;
进口java.io.FileOutputStream中;
进口的java.io.InputStream;
进口的java.net.URL;

进口android.app.Activity;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.graphics.drawable.BitmapDrawable;
进口android.graphics.drawable.Drawable;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ImageView;

公共类StackOverflowActivity延伸活动{

//
私人ImageView的mImageView;

/ **第一次创建活动时调用。 * /
@覆盖
公共无效的onCreate(包savedInstanceState){

    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    //找到参考的ImageView
    mImageView =(ImageView的)findViewById(R.id.test_image);

    //你可以在这里设置一个临时的背景
    //image.setImageResource(null);

    //启动DownloadImage任务与给定的URL
    新DownloadImage()执行(http://i.imgur.com/CQzlM.jpg);
}


/ **
 *简单的载体作用,设置一个可绘制的图像查看
 * @参数绘制
 * /
私人无效setImage(绘制对象绘制)
{
    mImageView.setBackgroundDrawable(绘制);
}

公共类DownloadImage扩展的AsyncTask<字符串,整数,可绘制> {

    @覆盖
    受保护的可绘制doInBackground(字符串...为arg0){
        //这是在后台线程完成
        返回downloadImage(为arg0 [0]);
    }

    / **
     *调用图像已被下载后,
     *  - >这再次呼吁在主线程功能
     * /
    保护无效onPostExecute(绘制的图像)
    {
        setImage(图像);
    }


    / **
     *其实从_url下载图片
     * @参数_url
     * @返回
     * /
    私人绘制对象downloadImage(字符串_url)
    {
        // prepare下载图片
        URL网址;
        的BufferedOutputStream出来;
        在的InputStream;
        的BufferedInputStream BUF;

        //的BufferedInputStream BUF;
        尝试 {
            URL =新的URL(_url);
            在= url.openStream();

            / *
             *这是没有必要
             *
             *您尝试创建的实际图像的位置,通过写
             *到新文件
             *您只需要读取的InputStream
             *和将其转换为位图
            OUT =新的BufferedOutputStream(新的FileOutputStream(testImage.jpg));
            INT I;

             而((ⅰ= in.read())!=  -  1){
                 out.write(ⅰ);
             }
             out.close();
             附寄();
             * /

            //读取的InputStream
            BUF =新的BufferedInputStream(中);

            //将的BufferedInputStream为位图
            位图BMAP = BitmapFactory.de codeStream(BUF);
            如果(在!= NULL){
                附寄();
            }
            如果(BUF!= NULL){
                buf.close();
            }

            返回新BitmapDrawable(BMAP);

        }赶上(例外五){
            Log.e(读取文件错误,e.toString());
        }

        返回null;
    }

}

}
 

不要忘了给permission.INTERNET添加到您的清单,如果没有,你会得到一个错误...

I have seen this question: android how to download an 1mb image file and set to ImageView
It does not solve my problem as it only shows how to display the bitmap after you already have it.

I am trying to download an image from a URL to have it be displayed with an ImageView on an Android device. I am not sure how to do this.

I've looked around a bit on the internet, this is the code I have so far:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //Set local image
    ImageView image = (ImageView) findViewById(R.id.test_image);
    image.setImageResource(R.drawable.test2);

    //Prepare to download image
    URL url;        
    InputStream in;

    //BufferedInputStream buf;
    try {
        url = new URL("http://i.imgur.com/CQzlM.jpg");
        in = url.openStream();

        out = new BufferedOutputStream(new FileOutputStream("testImage.jpg"));
        int i;

         while ((i = in.read()) != -1) {
             out.write(i);
         }
         out.close();
         in.close();

        buf = new BufferedInputStream(in);
        Bitmap bMap = BitmapFactory.decodeStream(buf);
        image.setImageBitmap(bMap);
        if (in != null) {
        in.close();
        }
        if (buf != null) {
        buf.close();
        }
    } catch (Exception e) {
        Log.e("Error reading file", e.toString());
    }
}

解决方案

The code would probably work, alltough you are downloading your image on your main thread. This means that when it takes more than 5 seconds to download, you will be presented with the famous ANR dialog, and your app will crash...

You should download your image in a background thread, and post the result back to your main thread. Back in the main thread, you can update your imageview with the downloaded image.

Here's an example:

package nl.entreco.stackoverflow;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class StackOverflowActivity extends Activity {

//  
private ImageView mImageView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Find the reference to the ImageView
    mImageView = (ImageView) findViewById(R.id.test_image);

    // You can set a temporary background here
    //image.setImageResource(null);

    // Start the DownloadImage task with the given url
    new DownloadImage().execute("http://i.imgur.com/CQzlM.jpg");
}


/**
 * Simple functin to set a Drawable to the image View
 * @param drawable
 */
private void setImage(Drawable drawable)
{
    mImageView.setBackgroundDrawable(drawable);
}

public class DownloadImage extends AsyncTask<String, Integer, Drawable> {

    @Override
    protected Drawable doInBackground(String... arg0) {
        // This is done in a background thread
        return downloadImage(arg0[0]);
    }

    /**
     * Called after the image has been downloaded
     * -> this calls a function on the main thread again
     */
    protected void onPostExecute(Drawable image)
    {
        setImage(image);
    }


    /**
     * Actually download the Image from the _url
     * @param _url
     * @return
     */
    private Drawable downloadImage(String _url)
    {
        //Prepare to download image
        URL url;        
        BufferedOutputStream out;
        InputStream in;
        BufferedInputStream buf;

        //BufferedInputStream buf;
        try {
            url = new URL(_url);
            in = url.openStream();

            /*
             * THIS IS NOT NEEDED
             * 
             * YOU TRY TO CREATE AN ACTUAL IMAGE HERE, BY WRITING
             * TO A NEW FILE
             * YOU ONLY NEED TO READ THE INPUTSTREAM 
             * AND CONVERT THAT TO A BITMAP
            out = new BufferedOutputStream(new FileOutputStream("testImage.jpg"));
            int i;

             while ((i = in.read()) != -1) {
                 out.write(i);
             }
             out.close();
             in.close();
             */

            // Read the inputstream 
            buf = new BufferedInputStream(in);

            // Convert the BufferedInputStream to a Bitmap
            Bitmap bMap = BitmapFactory.decodeStream(buf);
            if (in != null) {
                in.close();
            }
            if (buf != null) {
                buf.close();
            }

            return new BitmapDrawable(bMap);

        } catch (Exception e) {
            Log.e("Error reading file", e.toString());
        }

        return null;
    }

}

}

Don't forget to add the permission.INTERNET to your manifest, if not, you will get an error...

这篇关于下载图像的ImageView的在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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