2011-12-07 11 views
5

Tôi đã thấy câu hỏi này: android how to download an 1mb image file and set to ImageView
Nó không giải quyết vấn đề của tôi vì nó chỉ cho thấy làm thế nào để hiển thị bitmap sau bạn đã có nó.Tải hình ảnh cho ImageView trên Android

Tôi đang cố gắng tải xuống hình ảnh từ URL để hiển thị hình ảnh bằng ImageView trên thiết bị Android. Tôi không chắc chắn làm thế nào để làm điều này.

Tôi đã nhìn xung quanh một chút trên internet, đây là đoạn code tôi có cho đến nay:

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

Nếu bạn tìm thấy một câu trả lời, bạn nên chấp nhận nó. Bằng cách đó, những người dùng khác biết rằng nó hoạt động. Chúc may mắn! – Entreco

Trả lời

10

Mã này có lẽ sẽ làm việc, alltough bạn đang tải hình ảnh của bạn về chủ đề chính của bạn. Điều này có nghĩa là khi phải mất hơn 5 giây để tải xuống, bạn sẽ thấy hộp thoại ANR nổi tiếng và ứng dụng của bạn sẽ bị lỗi ...

Bạn nên tải xuống hình ảnh của mình trong chuỗi nền và đăng kết quả lại vào chủ đề chính của bạn. Quay lại chủ đề chính, bạn có thể cập nhật hình ảnh của mình bằng hình ảnh đã tải xuống.

Dưới đây là một ví dụ:

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

} 

} 

Đừng quên để thêm permission.INTERNET đến biểu hiện của bạn, nếu không, bạn sẽ nhận được một lỗi ...

+0

Tôi đã thử điều này. Nó không có lỗi, nhưng hình ảnh sẽ không tải. Quyền truy cập Internet ** là ** hiện diện trong tệp AndroidManifest.xml. Điều này có thể có một cái gì đó để làm với lớp DownloadImage được bên trong lớp khác? – Koen027

+0

Nevermind, tôi đã thay đổi mã một chút và nó hoạt động. Trong hàm setImage, tôi đã thay đổi dòng duy nhất thành: 'mImageView.setImageDrawable (drawable);' – Koen027

+0

Yar, xin lỗi về sự chờ đợi. Quên về điều này sau khi thử nghiệm nó ra. Thay vào đó, – Koen027