2009-04-23 44 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

相關問題