2015-10-06 69 views
0

我想從網址異步下載圖像,然後將其轉換爲位圖,我可以異步下載圖像沒有任何錯誤,但我發現很難將其轉換爲位圖。
轉換圖像下載到位圖

這裏是我的代碼

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

      // This is my image link 
      String url="www.myimagelink.com"; 

      // This downloads the image from the servers 
      new DownloadImage(ImageView).execute(url); 

      //this is suppose to convert my bitmap into a byteArray, but I cant seem to convert my image downloaded to a bitmap 

      final byte[] byteArray; 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      byteArray = stream.toByteArray(); 

     } 



    private class DownloadImage extends AsyncTask<String, Void, Bitmap> { 
     ImageView bmImage; 

     public DownloadImage(ImageView bmImage) { 
      this.bmImage = bmImage; 
     } 

     protected Bitmap doInBackground(String... urls) { 
      String urldisplay = urls[0]; 
      Bitmap mIcon11 = null; 
      try { 
       InputStream in = new java.net.URL(urldisplay).openStream(); 
       mIcon11 = BitmapFactory.decodeStream(in); 
      } catch (Exception e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return mIcon11; 
     } 

     protected void onPostExecute(Bitmap result) { 
      bmImage.setImageBitmap(result); 

     } 
    } 

} 

請我怎麼能轉換我的形象downlaoded成位圖?由於

+0

*但我發現很難將其轉換爲位圖。*您能詳細說明一下嗎? – Blackbelt

+0

您嘗試將位圖轉換爲byteArray必須在onPostExecute中執行,而不是在onCreate中,因爲asynctask不是阻塞調用,它將異步執行... –

+0

'請如何將我的圖像向下變換爲位圖?'。你已經在doInBackground中這樣做了。你讓doInBackgroud返回那個由onPostExcetute設置的Bitmap - 我認爲是ImageView。 – greenapps

回答

1

轉換你在字符串流然後解碼它爲位圖的財產以後這樣的:

String str = IOUtils.toString(in, encoding); 
byte[] decodedString = Base64.decode(str, Base64.NO_WRAP); 
Bitmap mIcon11 = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

使用此代碼在try塊......希望這會幫助你。

+0

請不要理解你的密碼,你可以簡單向我解釋一下,謝謝 – NewBIe

1
mIcon11 = BitmapFactory.decodeStream(in); 

mIcon11是一個位圖。

此外,

  1. 不要採用主線程長期運行opperation。這裏有關於異步android的很好的article;
  2. 我喜歡用Picasso下載圖片;