2010-04-07 89 views
1

我正在编写一个库来使C++与EPL2打印机语言接口。我希望尝试实现的一个功能是打印图像,规格文档中提到的将图像转换为单色字节数组

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

P2 =以点(或打印行)的图形的图形长度的长度,不图形文件格式

数据=原始二进制数据。数据必须以字节为单位。将字节宽度(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[])); 

任何帮助,即使它是在一个完全不同的方向非常赞赏。

+0

您正在寻找['LockBits'](http://msdn.microsoft.com/zh-cn/library/5ey6h79d%28v=VS.90%29.aspx)方法。 – SLaks 2010-04-07 15:42:04

+0

我使用了你的方法,但是遇到了我遇到的一个问题后续问题。 http://stackoverflow.com/questions/2595393/ – 2010-04-07 19:45:56

回答

0

由于SLaks said我需要使用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); 
} 
0

如果你只需要你的位图转换成字节数组,请尝试使用一个MemoryStream:

退房此链接:C# Image to Byte Array and 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(); 
}