I want to get image as byte array from database using local WCF service and display it on a Page using Image control. I cannot make it working.
This is the simplest code just to start… Eventually I want to use binding in XAML.
//I use following code for getting bytes (it’ s working)
private async Task GetPhotoAsync(string code)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get,
$"http://192.168.0.5/Service/TerminalService.svc/GetPhoto?Code={code}"))
{
using (var response = await httpClient.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
ImageBuffer = (await response.Content.ReadAsByteArrayAsync());
}
else
{
throw new Exception($"Error.{Environment.NewLine}{response}");
}
}
}
}
}
...
public byte[] ImageBuffer
{
get { return _imageBuffer; }
set { SetProperty(ref imageBuffer, value); }
}
public class BindableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null) eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
...
//Method used to convert bytes into BitmapImage and set source of control Image.
public async void SetImageFromByteArray(byte[] data, Image image)
{
using (InMemoryRandomAccessStream raStream = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(raStream))
{
// Write the bytes to the stream
writer.WriteBytes(data);
// Store the bytes to the MemoryStream
await writer.StoreAsync();
// Not necessary, but do it anyway
await writer.FlushAsync();
// Detach from the Memory stream so we don't close it
writer.DetachStream();
}
raStream.Seek(0);
BitmapImage bitMapImage = new BitmapImage();
bitMapImage.SetSource(raStream);
image.Source = bitMapImage;
}
}
When MainPage is loaded I run method GetPhotoAsync(). After a while I set Image.Source by pressing button and run method SetImageFromByteArray(). Nothing is displayed.
I also tried these solutions without success:
- with binding properties - https://marcominerva.wordpress.com/2013/04/15/how-to-convert-a-byte-array-to-image-in-a-windows-store-app/
- using converter - Windows Phone 8 - Load byte[] array into XAML image with Binding
- TaskCompletionNotifier - Async Implementation of IValueConverter