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

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

问题描述

我正在编写一个库来将 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)

Data = 没有图形文件格式的原始二进制数据.数据必须以字节为单位.将宽度以字节 (p1) 乘以打印行数 (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. The printer automatically calculates the exact size of the data block based upon this formula.

我计划我的源图像是一个 1 位/像素的 bmp 文件,已经缩放到大小.我只是不知道如何将它从该格式转换为 byte[] 以便我发送到打印机.我试过 ImageConverter.ConvertTo(Object,Type) 它成功了,但它输出的数组大小不正确,而且文档非常缺乏关于如何格式化输出的文档.

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.

推荐答案

As 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天全站免登陆