C# 从 URL 到流的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17876015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:42:51  来源:igfitidea点击:

Image from URL to stream

c#silverlightwindows-phone-7windows-phone-8

提问by Cheese

I'm getting images from a url:

我从一个 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();

And code fails with NullReference, how to fix it?

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

采纳答案by anderZubi

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

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

Other option is to get the stream of the image file directly using WebClient:

其他选项是直接使用 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));

回答by Ashok Damani

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

回答by Matsteel

you can use this:

你可以使用这个:

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