2009-12-24 74 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