如何从 Windows Phone 8.1 上的数据库获取图像并将其显示为字节数组
How to get and display image as byte array from database on Windows Phone 8.1
我想使用本地 WCF 服务从数据库中获取字节数组形式的图像,并使用图像控件将其显示在页面上。我无法让它工作。
这是刚开始的最简单的代码...最终我想在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;
}
}
加载 MainPage 时,我 运行 方法 GetPhotoAsync()。
过了一会儿,我通过按下按钮和 运行 方法 SetImageFromByteArray() 来设置 Image.Source。
什么都没有显示。
我也尝试了这些解决方案但没有成功:
- 具有绑定属性 -
https://marcominerva.wordpress.com/2013/04/15/how-to-convert-a-byte-array-to-image-in-a-windows-store-app/
- 使用转换器 -
Windows Phone 8 - Load byte[] array into XAML image with Binding
- TaskCompletionNotifier -
Async Implementation of IValueConverter
你可以试试这个,它对我有用。
首先,您必须在绑定图像控件的 ViewModel 中设置 属性。
public BitmapImage ImageSource
{
get { return _imageSource; }
set { SetProperty(ref _imageSource, value); }
}
...
public async Task GetPhotoAsync(string twrKod)
{
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)
{
var imageStream = await response.Content.ReadAsStreamAsync();
var memStream = new MemoryStream();
await imageStream.CopyToAsync(memStream);
memStream.Position = 0;
var bitmap = new BitmapImage();
bitmap.SetSource(memStream.AsRandomAccessStream())
ImageSource = bitmap;
}
}
}
}
}
确保您的 MemoryStream 是 return 类型的 WCF 服务。例如:
public Stream GetPhoto(string code)
{
byte[] bytes = null;
var myCommand = new SqlCommand())
myCommand.Connection = new SqlConnection(Settings.Default.ConnectionString);
objSql.ObjCommand.CommandText = "dbo.GetPhotoProc";
objSql.ObjCommand.CommandType = CommandType.StoredProcedure;
objSql.ObjCommand.Parameters.Add("@code", SqlDbType.NVarChar).Value = code;
objSql.Reader = objSql.ObjCommand.ExecuteReader();
if (!objSql.Reader.HasRows) return null;
while (objSql.Reader.Read())
{
bytes = (byte[])objSql.Reader.GetValue(0);
}
if (bytes == null) return Stream.Null;
var ms = new MemoryStream(bytes) { Position = 0 };
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return ms;
}
WCF 接口
[WebGet(UriTemplate = "GetPhoto?Code={code}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
Stream GetPhoto(string code);
我想使用本地 WCF 服务从数据库中获取字节数组形式的图像,并使用图像控件将其显示在页面上。我无法让它工作。
这是刚开始的最简单的代码...最终我想在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;
}
}
加载 MainPage 时,我 运行 方法 GetPhotoAsync()。 过了一会儿,我通过按下按钮和 运行 方法 SetImageFromByteArray() 来设置 Image.Source。 什么都没有显示。
我也尝试了这些解决方案但没有成功:
- 具有绑定属性 - https://marcominerva.wordpress.com/2013/04/15/how-to-convert-a-byte-array-to-image-in-a-windows-store-app/
- 使用转换器 - Windows Phone 8 - Load byte[] array into XAML image with Binding
- TaskCompletionNotifier - Async Implementation of IValueConverter
你可以试试这个,它对我有用。
首先,您必须在绑定图像控件的 ViewModel 中设置 属性。
public BitmapImage ImageSource
{
get { return _imageSource; }
set { SetProperty(ref _imageSource, value); }
}
...
public async Task GetPhotoAsync(string twrKod)
{
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)
{
var imageStream = await response.Content.ReadAsStreamAsync();
var memStream = new MemoryStream();
await imageStream.CopyToAsync(memStream);
memStream.Position = 0;
var bitmap = new BitmapImage();
bitmap.SetSource(memStream.AsRandomAccessStream())
ImageSource = bitmap;
}
}
}
}
}
确保您的 MemoryStream 是 return 类型的 WCF 服务。例如:
public Stream GetPhoto(string code)
{
byte[] bytes = null;
var myCommand = new SqlCommand())
myCommand.Connection = new SqlConnection(Settings.Default.ConnectionString);
objSql.ObjCommand.CommandText = "dbo.GetPhotoProc";
objSql.ObjCommand.CommandType = CommandType.StoredProcedure;
objSql.ObjCommand.Parameters.Add("@code", SqlDbType.NVarChar).Value = code;
objSql.Reader = objSql.ObjCommand.ExecuteReader();
if (!objSql.Reader.HasRows) return null;
while (objSql.Reader.Read())
{
bytes = (byte[])objSql.Reader.GetValue(0);
}
if (bytes == null) return Stream.Null;
var ms = new MemoryStream(bytes) { Position = 0 };
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return ms;
}
WCF 接口
[WebGet(UriTemplate = "GetPhoto?Code={code}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
Stream GetPhoto(string code);