2009-12-05 42 views
6

我想在Silverlight和WCF服務之間來回傳遞圖像的某種表示形式。如果可能的話,我想通過System.Windows.Media.Imaging.BitmapImage,因爲這意味着客戶端不必進行任何轉換。我可以從Silverlight中的BitmapImage獲取一個字節[]嗎?

然而,在某些時候,我需要這個圖像存儲在數據庫中,這意味着圖像表示必須能夠轉換和從byte[]。我可以通過讀取陣列分成MemoryStream和使用BitmapImage.SetSource()創建從一個byte[]BitmapImage。但我似乎無法找到轉換方式 - 從BitmapImagebyte[]。我在這裏錯過了很明顯的東西嗎

如果它有助於在所有的轉換代碼可以在服務器上運行,即,它並不需要Silverlight的安全。

+0

你有沒有得到一個解決方案? – 2010-05-10 14:00:04

+0

不是。圖像最初是通過用戶在打開的對話框中選擇它加載的。解決方法是訪問openDialog.File.OpenRead,從該流創建BinaryReader,然後在讀取器上調用ReadBytes()以獲取字節[]。我一直沒有跟上Silverlight 4,現在可能有一個解決方案。 – goric 2010-05-25 02:20:36

回答

6

使用此:

public byte[] GetBytes(BitmapImage bi) 
{ 
    WriteableBitmap wbm = new WriteableBitmap(bi); 
    return wbm.ToByteArray(); 
} 

public static byte[] ToByteArray(this WriteableBitmap bmp) 
{ 
    // Init buffer 
    int w = bmp.PixelWidth; 
    int h = bmp.PixelHeight; 
    int[] p = bmp.Pixels; 
    int len = p.Length; 
    byte[] result = new byte[4 * w * h]; 

    // Copy pixels to buffer 
    for (int i = 0, j = 0; i < len; i++, j += 4) 
    { 
     int color = p[i]; 
     result[j + 0] = (byte)(color >> 24); // A 
     result[j + 1] = (byte)(color >> 16); // R 
     result[j + 2] = (byte)(color >> 8); // G 
     result[j + 3] = (byte)(color);  // B 
    } 

    return result; 
} 
0

嘗試使用CopyPixels。您可以將位圖數據複製到一個字節數組。但是,我真的不確定像素的格式是什麼......它可能取決於最初加載的圖像類型。

+0

您鏈接的頁面一般用於.NET,BitmapSource的Silverlight版本(在System.Windows.dll中)不支持此方法:http://msdn.microsoft.com/zh-cn/library/system .windows.media.imaging.bitmapsource%28VS.95%29.aspx – goric 2009-12-05 03:11:13

+0

哦,道歉。我忘了Silverlight和WPF還不完全相同。 – jrista 2009-12-05 03:28:45

1

我有同樣的問題。 我發現ImageTools library可以讓你的工作更輕鬆。

獲取圖書館和參考,然後

     using (var writingStream = new MemoryStream()) 
         { 
          var encoder = new PngEncoder 
          { 
           IsWritingUncompressed = false 
          }; 
          encoder.Encode(bitmapImageInstance, writingStream); 
          // do something with the array 
         } 
相關問題