2011-12-07 14 views
5

Widziałem to pytanie: android how to download an 1mb image file and set to ImageView
To nie rozwiąże mój problem, jak to tylko pokazuje jak wyświetlić bitmapę po już masz go.Pobierz obraz ImageView na Androida

Próbuję pobrać obraz z adresu URL, aby był wyświetlany z obrazem na urządzeniu z systemem Android. Nie jestem pewien, jak to zrobić.

Mam rozejrzał się trochę w Internecie, jest to kod mam tak daleko:

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

Jeśli znalazłeś odpowiedź, ty powinien to zaakceptować. W ten sposób inni użytkownicy wiedzą, że to działa. Powodzenia! – Entreco

Odpowiedz

10

Kod prawdopodobnie działa, alltough pobierasz obraz na głównym wątku. Oznacza to, że jeśli pobieranie trwa dłużej niż 5 sekund, zostanie wyświetlone słynne okno dialogowe ANR, a aplikacja ulegnie awarii ...

Należy pobrać obraz w wątku tła i opublikować wynik z powrotem do głównego wątku. Wracając do głównego wątku, możesz zaktualizować swój podgląd obrazu z pobranym obrazem.

Oto przykład:

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

} 

} 

Nie zapomnij dodać permission.INTERNET aby Twój manifest, jeśli nie, dostaniesz błąd ...

+0

Próbowałem tego. Nie daje błędów, ale obraz się nie ładuje. Uprawnienia do Internetu ** są ** obecne w pliku AndroidManifest.xml. Czy to może mieć coś wspólnego z klasą DownloadImage znajdującą się wewnątrz innej klasy? – Koen027

+0

Nieważne, trochę zmieniłem kod i zadziałało. W funkcji setImage zmieniłem jedyną linię na: 'mImageView.setImageDrawable (drawable);' – Koen027

+0

Yar, przepraszam za czekanie. Zapomniałem o tym po przetestowaniu go. – Koen027

Powiązane problemy