我正在使用此方法从服务器同步下载图像数组
Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
try
{
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
}
catch
{
//Silence is gold.
}
displayPic();
return imageBitmap;
}
但我现在想要异步使用这个方法。我改变它看起来像这样
async Task<Bitmap> GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
try
{
using (var webClient = new WebClient())
{
var imageBytes = await webClient.DownloadStringTaskAsync(url);
if (imageBytes != null && imageBytes.Length > 0)
{
//imageBitmap = BitmapFactory.DecodeByteArray(Encoding.ASCII.GetBytes(imageBytes), 0, imageBytes.Length);
imageBitmap = BitmapFactory.DecodeByteArray(Encoding.BigEndianUnicode.GetBytes(imageBytes), 0, imageBytes.Length);
}
}
}
catch
{
//Silence is gold.
}
displayPic();
return imageBitmap;
}
但是从字符串到字节数组的转换不起作用,我每次都从方法中收到一个null
对象。
导致imageBitmap
变量在第二种方法中变为null
的原因是什么?我该如何解决?
答案 0 :(得分:0)
您将获得字节数组而不是字符串。改变这个:
var imageBytes = await webClient.DownloadStringTaskAsync(url);
到此:
var imageBytes = await webClient.DownloadDataTaskAsync(url);