位图到字节数组的转换

本文关键字:转换 数组 到字节 位图 | 更新日期: 2023-09-27 18:14:00

我需要将位图图像转换为字节数组,并使用热敏打印机打印它,其中每列的顶部像素是MSB,底部像素是LSB。目前,我的实现是这样的,但它没有像预期的那样打印图像:

Bitmap bitmap = (Bitmap)this.PictureBoxOriginalBitmap.Image;
int width, height;
width = bitmap.Width;
height = bitmap.Height;
byte[] data = new byte[height * width / 8];
uint counter = 0, index = 0;
byte[] sequence = new byte[8] { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
for (int rowIndex = 0; rowIndex < height / 8; rowIndex++)
{
 for (int columnIndex = 0; columnIndex < width; columnIndex++)
 {
       for (int pixelColumn = rowIndex * 8; pixelColumn < (rowIndex + 1) *8; pixelColumn++)
            {
                 data[counter] |= (byte)((bitmap.GetPixel(columnIndex, pixelColumn).R == 255) ? 0x00 : sequence[index]);
                 if (++index == 8)
                 {
                       counter++;
                       index = 0;
                 }
            }
      }
 }
StringBuilder message = new StringBuilder();
byte[] buffer;
this._bitmapInfo = new BitmapInformation();
buffer = new byte[width];
for (int rowIndex = 0; rowIndex < height / 8; rowIndex++)
{
     Array.Copy(data, width * rowIndex, buffer, 0, width);
     message.AppendLine(Helper.byteAsStringWith0x(buffer, true).Trim());
     this._bitmapInfo[rowIndex] =    Helper.byteAsStringWith0x(buffer,true).Trim();
}

位图到字节数组的转换

稍微重构一下你的解决方案。很安静,很难弄清楚发生了什么。测试了我的解决方案,在一个小的位图上,似乎我的解决方案是做正确的事情。至少按你的要求。

Bitmap bitmap = (Bitmap)this.PictureBoxOriginalBitmap.Image;
var width = bitmap.Width;
var height = bitmap.Height;
var shiftEnumerable = Enumerable.Range(0, 8).Reverse(); // create an array from (7..0) MSB as the first
var dataList = new List<byte>(); // Create a list instead of fiddeling with array indexes
for (int rowIndex = 7; rowIndex < height; rowIndex=rowIndex+8 ) // increment 8 pixels each iteration on y-axis. If picture is less than 8 pixels, convertion will not happen.
{
   for (int columnIndex = 0; columnIndex < width; columnIndex++) // increment x-axis
   {
       // Linq which performs a bitwise OR operation. Converts the predicate to byte and shifts result x places depending on which bit needs to be set.
       // Add the accumulated OR operation to a list of bytes.
       dataList.Add(shiftEnumerable.Aggregate<int, byte>(
                    0,
                    (accumulate, current) => (byte)(accumulate | (byte)(Convert.ToByte(bitmap.GetPixel(columnIndex, rowIndex - current).R == 255) << current))));
    }
}
// Convert List to array.
var data = dataList.ToArray();

这样做是因为这对我来说是一个有趣的练习。请让我知道你是否可以使用它:-)

编辑:

idx:  New  | Old
-----------------------
[0]:  170  | 170
[1]:  255  | 0
[2]:  127  | 1
[3]:  63   | 3
[4]:  31   | 7
[5]:  15   | 15
[6]:  7    | 31
[7]:  3    | 63
[8]:  129  | 126
[9]:  192  | 252
[10]: 224  | 248
[11]: 240  | 240
[12]: 248  | 224
[13]: 252  | 192
[14]: 254  | 128
[15]: 255  | 0

尝试比较data[]数组的输出,如您所见。