【问题标题】:Download image for imageview on Android在 Android 上下载 imageview 的图像
【发布时间】:2011-12-07 23:12:17
【问题描述】:

我看过这个问题:android how to download an 1mb image file and set to ImageView
它不能解决我的问题,因为它只显示了如何在 您已经拥有位图之后显示它。

我正在尝试从 URL 下载图像,以便在 Android 设备上与 ImageView 一起显示。我不知道该怎么做。

我在互联网上看了一些,这是我到目前为止的代码:

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

【问题讨论】:

  • 如果你找到了答案,你应该接受它。这样,其他用户就知道它有效。祝你好运!

标签: android download android-imageview


【解决方案1】:

代码可能会起作用,尽管您正在主线程上下载图像。这意味着当下载时间超过 5 秒时,您将看到著名的 ANR 对话框,并且您的应用程序将崩溃...

您应该在后台线程中下载您的图像,并将结果发布回您的主线程。回到主线程,您可以使用下载的图像更新您的 imageview。

这是一个例子:

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

}

}

不要忘记将permission.INTERNET添加到你的manifest中,如果没有,你会得到一个错误...

【讨论】:

  • 我试过这个。它没有错误,但图像不会加载。 AndroidManifest.xml 文件中存在互联网权限。这可能与另一个类中的 DownloadImage 类有关吗?
  • 没关系,我稍微更改了代码,它工作了。在 setImage 函数中,我将唯一的一行改为:mImageView.setImageDrawable(drawable);
  • Yar,抱歉让您久等了。测试后忘记了。
  • 函数 setBackgoundDrawable 已弃用,改为 setBackground。
猜你喜欢
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多