abc
abc

Reputation: 2437

24-bit- to 1-bit-bitmap-convertion

For a mobile application I have to generate a 1-bit-bitmap out of a 24-bit-bitmap. The problem is, that the result isn't correct, so i made this little project to try it on my desktop-pc. the creation works, but the result isn't ok, as you can see.

You can hardly read anything because a lot of bits aren't at the right position anymore but moved some pixels left or right.

This is the code i use for creation:

int z = 0;
int bitNumber = 0;
//the new 1Bit-byte-Array 
byte[] oneBitImage = new byte[(bmp.Height * bmp.Width) / 8];

BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
  byte* p = (byte*)(void*)bmData.Scan0.ToPointer();
  int stopAddress = (int)p + bmp.Height * bmData.Stride;
  while ((int)p != stopAddress)
  {
    if (*p < 128) // is black
    oneBitImage[z] = (byte)(oneBitImage[z] | Exp(bitNumber));   //Set a Bit on the specified position
    p += 3;

    bitNumber++;

    if (bitNumber == 8)
    {
      bitNumber = 0;
      z++;
    }
  }
}

bmp.UnlockBits(bmData);

//Convert into 1-bit-bmp to check result
Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format1bppIndexed);

BitmapData bmpData = newbmp.LockBits(
                             new Rectangle(0, 0, newbmp.Width, newbmp.Height),
                             ImageLockMode.WriteOnly, newbmp.PixelFormat);

Marshal.Copy(oneBitImage, 0, bmpData.Scan0, oneBitImage.Length);

newbmp.UnlockBits(bmpData);

newbmp.Save(fileName, ImageFormat.Bmp);

Short explanation: I run through every third byte, and if this byte - the first one of a 3-byte-group (pixel in 24-bit) - is lower than 128 I put a bit at the specified position. EXP gives me the exponent...

Upvotes: 1

Views: 2145

Answers (2)

AlexS
AlexS

Reputation: 354

I would convert three bytes to a "real" color (long value or similar) and see if the result is bigger than half of 16.7m .

Upvotes: 1

Mr Lister
Mr Lister

Reputation: 46569

Switch the bits in every output byte around. Bit 7 should be bit 0, etc.

Upvotes: 2

Related Questions