Image from URL to stream

前端 未结 3 2132
后悔当初
后悔当初 2020-12-18 19:50

I\'m getting images from a url:

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

This works p

相关标签:
3条回答
  • 2020-12-18 20:18

    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();
        }
    
    0 讨论(0)
  • 2020-12-18 20:20
    var webClient = new WebClient();
    byte[] imageBytes = webClient.DownloadData(article.ImageURL);
    
    0 讨论(0)
  • 2020-12-18 20:22

    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;
    

    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));
    
    0 讨论(0)
提交回复
热议问题