2009-12-24 71 views
6

我能一個byte []轉換爲圖像:的Silverlight:圖像爲byte []

byte[] myByteArray = ...; // ByteArray to be converted 

MemoryStream ms = new MemoryStream(my); 
BitmapImage bi = new BitmapImage(); 
bi.SetSource(ms); 

Image img = new Image(); 
img.Source = bi; 

但我不能夠將圖像轉換回一個byte []! 我在網上找到了一個解決方案,即對WPF的工作原理:

var bmp = img.Source as BitmapImage; 
int height = bmp.PixelHeight; 
int width = bmp.PixelWidth; 
int stride = width * ((bmp.Format.BitsPerPixel + 7)/8); 

byte[] bits = new byte[height * stride]; 
bmp.CopyPixels(bits, stride, 0); 

Silverlight的libary是如此的渺小,類的BitmapImage沒有財產稱爲格式!

有沒有人解決我的問題的想法。

我在網上搜索了很長時間才找到解決方案,但沒有解決方案,它在silverlight中工作!

謝謝!

回答

7

(每像素方法你缺少位只是細節的顏色信息是如何每像素存儲)

安東尼建議,一個WriteableBitmap的將是最簡單的方法 - 檢查http://kodierer.blogspot.com/2009/11/convert-encode-and-decode-silverlight.html的方法獲取ARGB字節數組出:

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

有沒有解決方案,在設計Silverlight的作品。可以檢索圖像,而無需像其他http請求必須符合任何跨域訪問策略。跨域規則放寬的基礎是構成圖像的數據不能在原始數據中檢索。它只能用作圖像。

如果您想簡單地寫入並從位圖圖像讀取,請使用WriteableBitmap類而不是BitmapImageWriteableBitmap公開Pixels財產BitmapImage上不可用。

2
public static void Save(this BitmapSource bitmapSource, Stream stream) 
    { 
     var writeableBitmap = new WriteableBitmap(bitmapSource); 

     for (int i = 0; i < writeableBitmap.Pixels.Length; i++) 
     { 
      int pixel = writeableBitmap.Pixels[i]; 

      byte[] bytes = BitConverter.GetBytes(pixel); 
      Array.Reverse(bytes); 

      stream.Write(bytes, 0, bytes.Length); 
     } 
    } 

    public static void Load(this BitmapSource bitmapSource, byte[] bytes) 
    { 
     using (var stream = new MemoryStream(bytes)) 
     { 
      bitmapSource.SetSource(stream); 
     } 
    } 

    public static void Load(this BitmapSource bitmapSource, Stream stream) 
    { 
     bitmapSource.SetSource(stream); 
    } 
+0

你有這方面的工作?特別是bitmapSource.SetSource(流);部分?爲我引發一個例外。 – jayarjo 2012-10-25 11:41:22