从URL到流的图像

时间:2013-07-26 08:00:44

标签: c# silverlight windows-phone-7 windows-phone-8

我从网址获取图片:

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而失败,如何解决?

3 个答案:

答案 0 :(得分:28)

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

答案 1 :(得分:15)

您收到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));

答案 2 :(得分:0)

你可以用这个:

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