本文介绍了从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;



另外一种选择是获得图像文件的数据流直接使用Web客户端:

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图像流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:35