Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image from URL to stream

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

And code fails with NullReference, how to fix it?

like image 997
Cheese Avatar asked Jul 26 '13 08:07

Cheese


People also ask

How do I get a stream URL?

The URL is found by right-clicking the browser page and choosing "Inspect Element." The Network tab will indicate the stream URLs. Save this answer.

How do I create a URL for an image?

Set the bitmap to your ImageView. And then this to ImageView like so: imageView. setImageBitmap(getBitmapFromURL(url));


2 Answers

var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData(article.ImageURL);
like image 73
Ashok Damani Avatar answered Oct 10 '22 18:10

Ashok Damani


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));
like image 23
anderZubi Avatar answered Oct 10 '22 16:10

anderZubi