2009-04-23 42 views
6

WCF服务中传递图像并在传递后将其显示在WPF数据网格中的最佳方式是什么?通过WCF传递图像,并将它们显示在WPF数据网格中

+0

您正在处理的图像的平均大小是多少?您需要在一次通话中处理多少人? 对于您的问题有几个很好的解决方案,但这取决于您在每次通话时必须处理的信息量。将它作为一个字节数组返回只是一个很好的解决方案,如果你的图像相对较小,并且你不必一次返回大量的数据(我问你是因为把它放在一个数据网格中,所以我 – 2009-05-10 14:22:20

回答

8

我并不是说这是唯一或最佳的解决方案,但我们有它的工作是这样的:

你需要做的是:

创建一个WCF方法将返回图像通过一些身份证或其他。它应该返回字节数组(byte []):

public byte[] GetImage(int id) 
{ 
    // put your logic of retrieving image on the server side here 
} 

在您的数据类(在网格中显示的对象)使属性的图像,其吸气剂应调用WCF方法和字节数组转换成的BitmapImage:

public BitmapImage Image 
{ 
    get 
    { 
    // here - connection is your wcf connection interface 
    //  this.ImageId is id of the image. This parameter can be basically anything 
    byte[] imageData = connection.GetImage(this.ImageId);  

    // Load the bitmap from the received byte[] array 
    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageData, 0, imageData.Length, false, true)) 
    { 
    BitmapImage bmp = new BitmapImage(); 
    bmp.BeginInit(); 
    bmp.StreamSource = stream; 

    try 
     { 
     bmp.EndInit(); 
     bmp.Freeze(); // helps for performance 

     return bmp; 
     } 
    catch (Exception ex) 
     { 
     // Handle exceptions here 
     } 

    return null; // return nothing (or some default image) if request fails 
    } 
    } 
} 

在你的模板(或地方)把一个Image控件和它的来源属性绑定到上面创建的图片属性:

<DataTemplate> <!-- Can be a ControlTemplate as well, depends on where and how you use it --> 
    <Image 
    Source={Binding Image, IsAsync=true} 
    /> 
</DataTemplate> 

不使UI自由的最简单方法当检索图像时将像我一样将IsAsync属性设置为false。但是还有很多需要改进的地方。例如。您可以在加载图像时显示一些加载动画。

使用PriorityBinding可以完成加载别的东西时显示的东西(您可以在这里阅读:http://msdn.microsoft.com/en-us/library/ms753174.aspx)。

0

你可以从流中加载WPF图像吗?如果是这样,那么你可以编写WCF服务来返回System.IO.Stream类型。

+1

我不知道这就是为什么我问 – 2009-04-24 07:10:21

+0

只要流被标记为唯一的一部分,你就可以发送一个流作为消息的一部分消息的正文,消息的其他所有字段都必须转到标题 – SaguiItay 2009-05-12 19:49:10

相关问题