Something like this might solve it for you.
using System.Drawing;
using System.Text;
using System;
namespace ParseTest
{
internal class Program
{
private const int Black = unchecked((int)0xFF000000);
private const int White = unchecked((int)0xFFFFFFFF);
private static bool IsValid(Color pixel)
{
var argb = pixel.ToArgb();
return argb == Black || argb == White;
}
private static int GetBlackBit(Color pixel) {
var argb = pixel.ToArgb();
return argb == Black ? 1 : 0;
}
static void Main()
{
var image = (Bitmap)Image.FromFile(@"C:\Temp\Input.png");
var result = new StringBuilder();
for (var y = 0; y < image.Size.Height; ++y)
{
for (var x = 0; x < image.Size.Width; x += 8)
{
var value = 0;
for (var i = 0; i < 8; ++i)
{
var pixel = image.GetPixel(x + i, y);
if (!IsValid(pixel))
throw new Exception("Image is not monochrome!!!");
value |= GetBlackBit(pixel) << (7 - i);
}
result.AppendFormat("0x{0:X2} ", value);
}
result.AppendLine();
}
Console.WriteLine(result);
}
}
}
(note that the example only works on images with a width that is a multiple of 8).
Note that you might get a performance boost from locking the bits and getting the data directly, but using pointers means you need to mark your code as
unsafe
.
Hope this helps,
Fredrik