17

我从一个网址获取图像:

BitmapImage image = new BitmapImage(new Uri(article.ImageURL));
NLBI.Thumbnail.Source = image;

这很完美,现在我需要把它放在一个流中,让它变成字节数组。我正在这样做:

WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();

并且代码因 NullReference 而失败,如何解决?

4

3 回答 3

35
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData(article.ImageURL);
于 2013-07-26T08:10:03.923 回答
16

你得到一个NullReference例外,因为当你使用它时图像仍然没有加载。您可以等待ImageOpened事件,然后使用它:

var image = new BitmapImage(new Uri(article.ImageURL));               
image.ImageOpened += (s, e) =>
    {
        image.CreateOptions = BitmapCreateOptions.None;
        WriteableBitmap wb = new WriteableBitmap(image);
        MemoryStream ms = new MemoryStream();
        wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
        byte[] imageBytes = ms.ToArray();
    };
NLBI.Thumbnail.Source = image;

其他选项是直接使用 WebClient 获取图像文件的流:

WebClient client = new WebClient();
client.OpenReadCompleted += (s, e) =>
     {
         byte[] imageBytes = new byte[e.Result.Length];
         e.Result.Read(imageBytes, 0, imageBytes.Length);

         // Now you can use the returned stream to set the image source too
         var image = new BitmapImage();
         image.SetSource(e.Result);
         NLBI.Thumbnail.Source = image;
     };
client.OpenReadAsync(new Uri(article.ImageURL));
于 2013-07-26T08:42:21.880 回答
1

你可以使用这个:

    private async Task<byte[]> GetImageAsByteArray(string urlImage, string urlBase)
    {

        var client = new HttpClient();
        client.BaseAddress = new Uri(urlBase);
        var response = await client.GetAsync(urlImage);

        return await response.Content.ReadAsByteArrayAsync();
    }
于 2018-01-25T18:39:34.403 回答