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));
WebClient
as shown above, then write the stream to a byte array and directly create the BitmapImage from the same stream by calling BitmapImage.SetSource. – Allhallows