我想從網址異步下載圖像,然後將其轉換爲位圖,我可以異步下載圖像沒有任何錯誤,但我發現很難將其轉換爲位圖。
轉換圖像下載到位圖
這裏是我的代碼
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成位圖?由於
*但我發現很難將其轉換爲位圖。*您能詳細說明一下嗎? – Blackbelt
您嘗試將位圖轉換爲byteArray必須在onPostExecute中執行,而不是在onCreate中,因爲asynctask不是阻塞調用,它將異步執行... –
'請如何將我的圖像向下變換爲位圖?'。你已經在doInBackground中這樣做了。你讓doInBackgroud返回那個由onPostExcetute設置的Bitmap - 我認爲是ImageView。 – greenapps