【发布时间】:2016-04-03 02:52:18
【问题描述】:
我正在尝试从 url 异步下载图像,然后将其转换为位图,我能够异步下载图像而没有任何错误,但我发现很难将其转换为位图。
这是我的代码
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);
}
}
}
请问如何将下载的图像转换为位图?谢谢
【问题讨论】:
-
但我发现很难将其转换为位图。您能详细说明一下吗?
-
您将位图转换为 byteArray 的尝试必须在 onPostExecute 中进行,而不是在 onCreate 中,因为 asynctask 不是阻塞调用,它将异步发生...
-
'请问如何将下载的图像转换为位图?'。您已经在 doInBackground 中这样做了。然后你让 doInBackgroud 返回那个位图,然后由 onPostExcetute 设置 - 我认为是一个 ImageView。