我可以从在Silverlight中的BitmapImage一个byte []?
-
13-09-2019 - |
题
我试图传递一个图像的一些表示来回Silverlight和WCF服务之间。如果可能的话,我想传递一个System.Windows.Media.Imaging.BitmapImage
,因为这将意味着客户不必做任何转换。
然而,在某些时候,我需要这个图像存储在数据库中,这意味着图像表示必须能够转换和从byte[]
。我可以通过读取阵列分成BitmapImage
和使用byte[]
创建从一个MemoryStream
BitmapImage.SetSource()
。但我似乎无法找到一种方法,另一种方式转换 - 从BitmapImage
到byte[]
。我失去了一些东西明显在这里?
如果它有助于在所有的转换代码可以在服务器上运行,即,它并不需要Silverlight的安全。
解决方案
使用这样的:
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;
}
其他提示
我有同样的问题。 我发现 ImageTools库使thte工作方式更容易。
获取库和引用它,然后
using (var writingStream = new MemoryStream())
{
var encoder = new PngEncoder
{
IsWritingUncompressed = false
};
encoder.Encode(bitmapImageInstance, writingStream);
// do something with the array
}
尝试使用 CopyPixels 。您可以将位图数据复制到一个字节数组。不过,我真的不知道是什么的像素格式是......它可能是依赖于最初装的那种形象。
不隶属于 StackOverflow