位图到字节数组转换

时间:2016-10-20 06:22:47

标签: c# bitmap

我需要将位图图像转换为字节数组并使用热敏打印机进行打印,其中每列的顶部像素为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();
}

1 个答案:

答案 0 :(得分:0)

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

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[]数组的输出,如您所见。我们的结果完全不同。