How to get and display image as byte array from database on Windows Phone 8.1

Mike

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:

mdziadowiec

You can try this, it works for me.

First you have to set up property in your ViewModel which you bind the Image control to.

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;
                    }

                }
            }
        }
    }

Make sure you have MemoryStream to be return type of WCF Service. For example:

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;
    }

Interface for WCF

[WebGet(UriTemplate = "GetPhoto?Code={code}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
    [OperationContract]
    Stream GetPhoto(string code);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

how to get email, display name, number using the phone number chooser task for Windows Phone 8

来自分类Dev

Windows Phone 8 Image Binding

来自分类Dev

Windows Phone 8的Http GET请求

来自分类Dev

Windows Phone 8中BitmapImage / Image控件的内存消耗

来自分类Dev

在Windows Phone 8 C#中,将Stream转换为byte []数组始终返回0长度

来自分类Dev

如何确定Windows Phone 8(.1)上的蓝牙是否打开

来自分类Dev

How to run the Windows Phone Emulator without Windows 8 Pro?

来自分类Dev

Windows Phone 8 HttpClient Get方法返回奇怪的结果

来自分类Dev

Windows Phone 8记录

来自分类Dev

Windows Phone 8的LockScreen

来自分类Dev

Windows Phone 8记录

来自分类Dev

How to get 8 random unique elements from a string array?

来自分类Dev

“ Windows Phone Silverlight 8”是否与“ Windows Phone 8”相同?

来自分类Dev

在Windows Phone 8中将Dictionary <string,string>转换/序列化为字节数组byte []

来自分类Dev

在Windows Phone 8中将Dictionary <string,string>转换/序列化为字节数组byte []

来自分类Dev

Windows Phone 8:显示pdf

来自分类Dev

Windows Phone 8中的NavigationDrawer

来自分类Dev

Windows Phone 8蓝牙开发

来自分类Dev

Windows Phone 8图像绑定

来自分类Dev

Windows Phone 8-PriorityBinding

来自分类Dev

SetSysTrayVisible错误Windows Phone 8

来自分类Dev

从代码锁定Windows Phone 8

来自分类Dev

对Windows Phone 8使用WNS

来自分类Dev

滚动浏览Windows Phone 8

来自分类Dev

Windows Phone 8进度栏

来自分类Dev

Windows Phone 8 WCF同步

来自分类Dev

Windows Phone 8 AppBar命令

来自分类Dev

Windows Phone 8的Cordova问题

来自分类Dev

从代码锁定Windows Phone 8