Get 1 BitPerPixel color

M

Morten Nielsen

I'm trying to manipulate a 1bpp image.
I have found this example to set a pixel :

private unsafe void SetIndexedPixel(int x,int y,BitmapData bmd, bool pixel)
{
byte* p = (byte*)bmd.Scan0.ToPointer();
int index = y * bmd.Stride + (x >> 3);
byte mask = (byte)(0x80 >> (x & 0x7));

if (pixel)
p[index]|=mask;
else
p[index]&=(byte)(mask^0xff);
}
....which seems to work ok, but I haven't been able to find an example of
doing a GetIndexedPixel(), so I tried myself :

protected unsafe bool GetIndexedPixel(int x,int y,BitmapData bmd)
{
byte* p=(byte*)bmd.Scan0.ToPointer();
int index=y*bmd.Stride+(x>>3);
byte mask=(byte)(0x80>>(x&0x7));
return (p[index]==mask);
}

But this only works for less than 1% of the pixels! There's a lot of
assignents and byte-manipulation in the SetIndexedPixel method that I don't
really understand, so I'm not sure if my GetIndexedPixel is correct at all
(something tells me its not). Can anyone spot the error?

Regards
/Morten Nielsen
http://www.iter.dk
 
J

John Vottero

Morten Nielsen said:
I'm trying to manipulate a 1bpp image.
I have found this example to set a pixel :

private unsafe void SetIndexedPixel(int x,int y,BitmapData bmd, bool pixel)
{
byte* p = (byte*)bmd.Scan0.ToPointer();
int index = y * bmd.Stride + (x >> 3);
byte mask = (byte)(0x80 >> (x & 0x7));

if (pixel)
p[index]|=mask;
else
p[index]&=(byte)(mask^0xff);
}
...which seems to work ok, but I haven't been able to find an example of
doing a GetIndexedPixel(), so I tried myself :

protected unsafe bool GetIndexedPixel(int x,int y,BitmapData bmd)
{
byte* p=(byte*)bmd.Scan0.ToPointer();
int index=y*bmd.Stride+(x>>3);
byte mask=(byte)(0x80>>(x&0x7));
return (p[index]==mask);

I think the last line is wrong, it should be:

return ((p[index] & mask) != 0);

You are comparing an entire byte to a bit mask that has a single bit set.
You should be using the mask to AND out only the relevant bit and then check
to see if it's set.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top