一个图像转换为单色字节数组 [英] Convert a image to a monochrome byte array

查看:196
本文介绍了一个图像转换为单色字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的接口C#与EPL2打印机语言库。一个功能,我想尝试实施的打印图像,规范医生说。

I am writing a library to interface C# with the EPL2 printer language. One feature I would like to try to implement is printing images, the specification doc says

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

p1 = Width of graphic Width of graphic in bytes. Eight (8) dots = one (1) byte of data.

P2 =在点(或打印线)图形的图形长度

p2 = Length of graphic Length of graphic in dots (or print lines)

数据=原始二进制数据的长度没有图形文件格式。数据必须以字节为单位。乘在由印刷线路(P2)用于图形数据的总量的字节数(P1)的宽度。打印机会自动计算根据这个公式中的数据块的确切大小。

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. The printer automatically calculates the exact size of the data block based upon this formula.

我计划在我的源图像是每1位像素bmp文件,已经扩展到大小。我只是不知道如何从这种格式得到它到一个byte []为我送行到打印机。我试着 ImageConverter.ConvertTo (对象类型) 它成功,但它输出数组是不正确的大小和文档的输出如何格式化十分欠缺。

I plan on my source image being a 1 bit per pixel bmp file, already scaled to size. I just don't know how to get it from that format in to a byte[] for me to send off to the printer. 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.

我目前的测试代码。

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.

推荐答案

作为的 SLaks说我需要使用LockBits

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

这篇关于一个图像转换为单色字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆