ImageLockMode enumeration semantics

G

Guest

Hi,
the Bitmap.LockBits method takes the ImageLockMode enumeration as a
parameter. I may be missing something but if I supply a value of
ImageLockMode.ReadOnly to the LockBits method I am still able to change the
pixel values. Maybe I am missing something, but I would think that I should
not be able to change the values, or does this enumeration mean something
else?

Some sample code to set the Red component of an image to full for every
pixel, with the ReadOnly property passed into the LockBits method:

public unsafe void ProcessImage(Bitmap image)
{
Rectangle rectangle = new Rectangle(0, 0, image.Width,
image.Height);
BitmapData bitmapData = image.LockBits(rectangle,
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

//current pixel we are processing
byte* currentPixel = (byte*)bd.Scan0.ToPointer();

//end address when we should stop, which is
//start + number of pixels * 3 for 3bytes per pixel
byte* endPointer = currentPixel + image.Width * image.Height * 3;

//loop through all pixels in image
while (ptr != endPointer)
{
byte* endOfRow = currentPixel + bitmapData.Stride;

//loop through pixels in current row
while (currentPixel != endOfRow)
{
//set red component to full
currentPixel[2] = 255;

//move to next pixel
currentPixel += 3;
}

//move past padding to start of new row
currentPixel += bitmapData.Stride - (image.Width * 3);
}

//Put data back into bitmap object
image.UnlockBits(bd);
}


Thanks
Mark.
 
G

Guest

sorry, here is a version of the code which actually compiles :p

public unsafe void ProcessImage(Bitmap image)
{
Rectangle rectangle = new Rectangle(0, 0, image.Width,
image.Height);
BitmapData bitmapData = image.LockBits(rectangle,
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

//current pixel we are processing
byte* currentPixel = (byte*)bitmapData.Scan0.ToPointer();

//end address when we should stop, which is
//start + number of pixels * 3 for 3bytes per pixel
byte* endPointer = currentPixel + image.Width * image.Height * 3;

//loop through all pixels in image
while (currentPixel != endPointer)
{
byte* endOfRow = currentPixel + bitmapData.Stride;

//loop through pixels in current row
while (currentPixel != endOfRow)
{
//set red component to full
currentPixel[2] = 255;

//move to next pixel
currentPixel += 3;
}

//move past padding to start of new row
currentPixel += bitmapData.Stride - (image.Width * 3);
}

//Put data back into bitmap object
image.UnlockBits(bitmapData);
}
 

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