从 URL 到流的图像 [英] Image from URL to stream

查看:19
本文介绍了从 URL 到流的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个 url 获取图像:

I'm getting images from a url:

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

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

This works perfect, now i need to put it in a stream, to make it into byte array. I'm doing this:

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

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

推荐答案

您收到 NullReference 异常,因为在您使用图像时仍未加载该图像.您可以等待 ImageOpened 事件,然后使用它:

You get a NullReference exception because the image is still not loaded when you use it. You can wait to the ImageOpened event, and then work with it:

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 获取图像文件的流:

Other option is to get the stream of the image file directly using 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));

这篇关于从 URL 到流的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆