将图像转换为单色字节数组

我正在编写一个库,用CPL与EPL2打印机语言接口。 规范文档说,我想尝试实现的一个function是打印图像

p1 =图形宽度图形宽度,以字节为单位。 八(8)个点=一(1)个数据字节。

p2 =图形长度以点(或打印行)为单位的图形长度

Data =原始二进制数据,没有图形文件格式。 数据必须以字节为单位。 将宽度(以字节为单位)(p1)乘以图形数据总量的打印行数(p2)。 打印机根据此公式自动计算数据块的确切大小。

我计划我的源图像是每像素1位bmp文件,已经缩放到大小。 我只是不知道如何从那个格式到一个字节[]让我发送到打印机。 我尝试ImageConverter.ConvertTo(Object, Type)它成功但它输出的数组不是正确的大小和文档非常缺乏如何格式化输出。

我目前的测试代码。

 Bitmap i = (Bitmap)Bitmap.FromFile("test.bmp"); ImageConverter ic = new ImageConverter(); byte[] b = (byte[])ic.ConvertTo(i, typeof(byte[])); 

即使它处于完全不同的方向,也非常感谢任何帮助。

如果您只需要将位图转换为字节数组,请尝试使用MemoryStream:

看看这个链接: C#Image to Byte Array和Byte Array to Image Converter Class

 public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } 

正如SLaks所说,我需要使用LockBits

 Rectangle rect = new Rectangle(0, 0, Bitmap.Width, Bitmap.Height); System.Drawing.Imaging.BitmapData bmpData = null; byte[] bitVaues = null; int stride = 0; try { bmpData = Bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, Bitmap.PixelFormat); IntPtr ptr = bmpData.Scan0; stride = bmpData.Stride; int bytes = bmpData.Stride * Bitmap.Height; bitVaues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, bitVaues, 0, bytes); } finally { if (bmpData != null) Bitmap.UnlockBits(bmpData); }