从URL到流的图像

本文关键字:图像 URL | 更新日期: 2023-09-27 18:24:57

我正在从一个url获取图像:

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失败,如何修复

从URL到流的图像

var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData(article.ImageURL);

您会得到一个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));

您可以使用这个:

    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();
    }