The complete question is how to display an image downloaded from a database in Windows Phone 8.1. Image data is loaded as an array of bytes (checked - load fine).
Displaying an image using urisource hint works fine.
Image img = new Image(); img.Source = new BitmapImage() {UriSource = new Uri("http://www.example.com/1.jpg") }; rootgrid.Children.Add(img);
But when an array of bytes (images) is converted to BitmapImage - nothing is displayed. The only exclusive example I have found so far:
public BitmapImage ConvertToBitmapImage(byte[] image) { InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream(); var bitmapImage = new BitmapImage(); var memoryStream = new MemoryStream(image); memoryStream.CopyToAsync(ras.AsStreamForWrite()); bitmapImage.SetSourceAsync(ras); return bitmapImage; } Image img = new Image(); img.Source = ConvertToBitmapImage(picturebytearray); rootgrid.Children.Add(img);
But then the image is not displayed.
The Microsoft documentation contains only an example of loading images from a stream, which is obtained by opening a file from internal storage. But I need to upload an image which is saved in sqlite database. Image data is in jpeg format.
Edit: Working code based on freshbm :
public async Task<BitmapImage> ConvertToBitmapImage(byte[] image) { BitmapImage bitmapimage = null; using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0))) { writer.WriteBytes((byte[])image); await writer.StoreAsync(); } bitmapimage = new BitmapImage(); bitmapimage.SetSource(ms); } return bitmapimage; }
Then in the constructors you can use:
img.Source = ConvertToBitmapImage(imagebytearray).Result;
or more
img.Source = await ConvertToBitmapImage(imagebytearray);
c # image windows-phone byte
Artur alexeev
source share