如何在C#中将8位灰度图像转换为byte []数组?
问题描述:
如何将8位灰度图像的数据放入字节数组中?我试过以下代码:如何在C#中将8位灰度图像转换为byte []数组?
private byte[] loadBitmap(string filename, int width, int height)
{
byte[] data = new byte[width * height];
BitmapData bmpData = null;
Bitmap slice = new Bitmap(filename);
Rectangle rect = new Rectangle(0, 0, slice.Width, slice.Height);
bmpData = slice.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
int size = bmpData.Height * bmpData.Stride;
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, data, 0, size);
slice.UnlockBits(bmpData);
return data;
}
但是由于Format8bppIndexed数据数组的结果有一些错误。有任何想法吗?
答
我不知道这是否能帮助你,但我会尝试。
byte[] buffer = null;
System.Drawing.Image newImg = img.GetThumbnailImage(width, height, null, new System.IntPtr());
using (MemoryStream ms = new MemoryStream()) {
newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
buffer = ms.ToArray();
这只是我已经完成的一种方式。
希望它有帮助
+0
它不起作用 – 2011-02-11 10:14:54
您的代码示例“适用于我的机器”。 Format8bppIndexed适用于8位灰度。测试图像的宽度是多少?源尺寸为“高度*步幅”,但您的目标尺寸仅为“宽度*高度”。所以如果由于DWORD对齐而导致位图包含填充,看起来您也在复制此填充,并且可能会超出缓冲区。 – 2011-02-11 13:38:28