简体   繁体   English

如何在Windows Phone 8.1上从数据库获取和显示图像作为字节数组

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

I want to get image as byte array from database using local WCF service and display it on a Page using Image control. 我想使用本地WCF服务从数据库获取图像作为字节数组,并使用Image控件在页面上显示它。 I cannot make it working. 我不能让它发挥作用。

This is the simplest code just to start… Eventually I want to use binding in XAML. 这是最简单的代码才能开始...最终我想在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(). 加载MainPage时,我运行方法GetPhotoAsync()。 After a while I set Image.Source by pressing button and run method SetImageFromByteArray(). 过了一会儿,我按下按钮设置Image.Source并运行方法SetImageFromByteArray()。 Nothing is displayed. 没有显示任何内容。

I also tried these solutions without success: 我也试过这些解决方案但没有成功:

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. 首先,您必须在ViewModel中设置属性,并将Image控件绑定到该属性。

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. 确保将MemoryStream作为WCF服务的返回类型。 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 WCF的接口

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Windows Phone 8.1中加载,显示,转换来自字节数组(数据库)的图像 - Load, show, convert image from byte array (database) in Windows Phone 8.1 如何使用解决方案中的图像制作字节数组。 (Windows Phone 8.1运行时) - How to make a byte array with an image from solution. (Windows Phone 8.1 runtime) 在Windows Phone 8.1中将字节数组转换为图像的同步方法 - Synchronous way to convert byte array to image in Windows Phone 8.1 如何使用c#将图像转换为Windows Phone 8.1中的字节数组 - How to convert an image to byte array in windows phone 8.1 using c# 在Windows Phone 8.1中将IBuffer转换为字节数组,怎么样? - Convert an IBuffer to a byte array in Windows Phone 8.1, how? Windows Phone 8.1从base64字符串获取图像 - Windows Phone 8.1 get image from base64 string Windows Phone 8.1将图像从imageview获取到BitmapImage - Windows phone 8.1 get image from imageview to BitmapImage 从Windows Phone 8.1中的Image获取Jpeg属性 - Get Jpeg properties from Image in Windows Phone 8.1 如何从Windows Phone 8.1中的Assets文件夹中获取图像并将其分配给模型的属性 - How to get image from assets folder in windows phone 8.1 and assign it to a model's property 将WriteableBitmap转换为Byte数组 - Windows Phone 8.1 - Silverlight - Converting WriteableBitmap to Byte array - Windows phone 8.1 - Silverlight
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM