Direct memory-access GetPixel()-method returns 0 instead of 255

M

Morten Nielsen

Does anyone have any idea why I can't get a pixel-value of 255 returned in
the code below?
Any color-value from 0 up to 254 is returned correctly, but any
color-component of 255 returns zero. ie. bright white pixel would return
0,0,0 with the function below: The color (234,123,255) returns (234,123,0).

I would have thought that the byte value could hold values from 0..255 and
not only 0..254. At least thats what the C# specs and my common sense tell
me :)

/// <summary>
/// Gets the color of a 24bit-pixel by using direct access to memory
/// </summary>
/// <param name="x">Row</param>
/// <param name="y">Column</param>
/// <returns>Color of pixel at (row,column)</returns>
public unsafe Color GetPixel(int x, int y)
{
byte* p = (byte *)bmd.Scan0 + y*bmd.Stride + 3*x;
return Color.FromArgb(p[2],p[1],p[0]);
}

where bmd is declared as:
private BitmapData bmd = myBitmap.LockBits(new Rectangle(0, 0,
myBitmap.Width, myBitmap.Height), ImageLockMode.ReadWrite,
myBitmap.PixelFormat);

I have checked that (myBitmap.PixelFormat==PixelFormat.Format24bppRgb) is
true.

Any help or ideas are appreciated

Regards
/Morten Nielsen
www.dotnetgis.net
 
F

fd123456

Hi Morten,

Using your exact same code, I do get 255s!

Using a 4x4 test bmp with several colors (including black, white, red,
green, blue, magenta, cyan and yellow), with a textbox called "tb" :



BitmapData bmd ;

public unsafe Color GetPixel(int x, int y)
{
byte* p = (byte *)bmd.Scan0 + y*bmd.Stride + 3*x;
return Color.FromArgb(p[2],p[1],p[0]);
}

private void button1_Click(object sender, EventArgs e)
{
Bitmap myBitmap = new Bitmap("C:\\test.bmp");
bmd = myBitmap.LockBits(new Rectangle(0, 0,myBitmap.Width,
myBitmap.Height), ImageLockMode.ReadWrite, myBitmap.PixelFormat);

for (int y = 0 ; y < 4 ; y++)
{
for (int x = 0 ; x < 4 ; x++)
{
tb.AppendText(GetPixel(x,y) + Environment.NewLine);
}
}
}

This returns :

Color [A=255, R=255, G=255, B=255]
Color [A=255, R=0, G=0, B=0]
Color [A=255, R=255, G=0, B=0]
Color [A=255, R=255, G=255, B=0]
Color [A=255, R=0, G=255, B=0]
Color [A=255, R=0, G=255, B=255]
Color [A=255, R=0, G=0, B=255]
Color [A=255, R=255, G=0, B=255]
<snip>

So I believe that your error lies not in your reading routine, which
is fine, but in your "color returns". How exactly do you read the
color's values?

HTH,

Michel
 

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