简体   繁体   English

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

[英]Convert a image to a monochrome byte array

I am writing a library to interface C# with the EPL2 printer language. 我正在编写一个库,以将C#与EPL2打印机语言接口。 One feature I would like to try to implement is printing images, the specification doc says 规范文档说,我想尝试实现的一项功能是打印图像

p1 = Width of graphic Width of graphic in bytes. p1 =图形宽度图形宽度(以字节为单位)。 Eight (8) dots = one (1) byte of data. 八(8)点=一(1)字节的数据。

p2 = Length of graphic Length of graphic in dots (or print lines) p2 =图形长度图形长度(以点(或打印线)为单位)

Data = Raw binary data without graphic file formatting. 数据=没有图形文件格式的原始二进制数据。 Data must be in bytes. 数据必须以字节为单位。 Multiply the width in bytes (p1) by the number of print lines (p2) for the total amount of graphic data. 将图形数据总量的字节宽度(p1)乘以打印行数(p2)。 The printer automatically calculates the exact size of the data block based upon this formula. 打印机根据此公式自动计算数据块的确切大小。

I plan on my source image being a 1 bit per pixel bmp file, already scaled to size. 我计划我的源图像是每像素bmp文件1位的大小,已经按比例缩放了。 I just don't know how to get it from that format in to a byte[] for me to send off to the printer. 我只是不知道如何将其从该格式输入到byte []中,以便发送给打印机。 I tried ImageConverter.ConvertTo(Object, Type) it succeeds but the array it outputs is not the correct size and the documentation is very lacking on how the output is formatted. 我尝试了ImageConverter.ConvertTo(Object, Type)成功,但是它输出的数组大小不正确,关于如何格式化输出的文档也很缺乏。

My current test code. 我当前的测试代码。

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

Any help is greatly appreciated even if it is in a totally different direction. 即使在完全不同的方向上提供任何帮助,也将不胜感激。

As SLaks said I needed to use LockBits 正如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);
}

If you just need to convert your bitmap into a byte array, try using a MemoryStream: 如果只需要将位图转换为字节数组,请尝试使用MemoryStream:

Check out this link: C# Image to Byte Array and Byte Array to Image Converter Class 签出此链接: C#图像到字节数组和字节数组到图像转换器类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM