I'm trying to convert a byte array from an image that is in Raster
format, which reads from left to right, to Column
format, which reads from top to bottom.
The problem looks simple, we have two-dimensional array of bits (width/height of image). In Raster
format, you read the bits from left to right, in Column
format you read the bits from top to bottom.
I try to do this to support Column
format printing of the ESC/POS
protocol. I already have the image in Raster
format, now I'm trying to convert it to Column
format.
ESC/POS
documentation of Raster
printing:
ESC/POS
documentation of the Column
printing:
- https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=106#gs_lparen_cl_fn68
- https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=90
For the moment, I make the conversion by working on the bits directly with BitArray
. This solution is not optimal, it would be necessary to work directly in Byte
in my opinion.
private byte[] ConvertRasterToColumnFormat(byte[] rasterData, int width, int height)
{
var finalHeight = height;
while (finalHeight % 8 != 0) finalHeight++;
var finalWidth = width;
while (finalWidth % 8 != 0) finalWidth++;
var rasterBitArray = new BitArray(rasterData);
var columnBitArray = new BitArray(finalHeight * finalWidth);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
var rasterPosition = y * finalWidth;
var columnPosition = x * finalHeight;
rasterPosition += (x / 8) * 8;
columnPosition += (y / 8) * 8;
rasterPosition += 7 - x % 8;
columnPosition += 7 - y % 8;
var value = rasterBitArray[rasterPosition];
columnBitArray[columnPosition] = value;
}
}
var result = new byte[columnBitArray.Length / 8];
columnBitArray.CopyTo(result, 0);
return result;
}
.NET Fiddle with Tests: https://dotnetfiddle.net/NBRBgt
Does anyone have a more optimal solution?