Ok, so I'm using some code that adjusts an images contrast:
public static Bitmap AdjustContrast(Bitmap Image, float Value)
{
Value = (100.0f + Value) / 100.0f;
Value *= Value;
Bitmap NewBitmap = (Bitmap)Image.Clone();
BitmapData data = NewBitmap.LockBits(new Rectangle(0, 0, NewBitmap.Width, NewBitmap.Height), ImageLockMode.ReadWrite, NewBitmap.PixelFormat);
unsafe
{
for (int y = 0; y < NewBitmap.Height; ++y)
{
byte* row = (byte*)data.Scan0 + (y * data.Stride);
int columnOffset = 0;
for (int x = 0; x < NewBitmap.Width; ++x)
{
try
{
byte B = row[columnOffset];
byte G = row[columnOffset + 1];
byte R = row[columnOffset + 2];
float Red = R / 255.0f;
float Green = G / 255.0f;
float Blue = B / 255.0f;
Red = (((Red - 0.5f) * Value) + 0.5f) * 255.0f;
Green = (((Green - 0.5f) * Value) + 0.5f) * 255.0f;
Blue = (((Blue - 0.5f) * Value) + 0.5f) * 255.0f;
int iR = (int)Red;
iR = iR > 255 ? 255 : iR;
iR = iR < 0 ? 0 : iR;
int iG = (int)Green;
iG = iG > 255 ? 255 : iG;
iG = iG < 0 ? 0 : iG;
int iB = (int)Blue;
iB = iB > 255 ? 255 : iB;
iB = iB < 0 ? 0 : iB;
row[columnOffset] = (byte)iB;
row[columnOffset + 1] = (byte)iG;
row[columnOffset + 2] = (byte)iR;
columnOffset += 4;
}
catch (AccessViolationException av)
{
MessageBox.Show("Access violation!");
}
}
}
}
NewBitmap.UnlockBits(data);
return NewBitmap;
}
It seemed to be working fine. I could load an image and make ajustments using this method. I have another two methods for brightness and scaling which don't have unsafe code. They don't cause any problems. Anyway, all of a sudden I seem to get an access violation that only occurs when altering colour images. It occurs in this line:
byte B = row[columnOffset];
But not in the first iteration. For example when I use an image that's Width = 1024, Height = 1184, the error occurs when columnOffset reaches 3072.
I'm stuck for ideas as to what the problem is as surely it should treat a greyscale image the same as a colour one.
Help would be much appreciated.
And yes, I could try another contrast adjustment method, which I will. But I'd really like to know what the problem is here - morbid curiosity perhaps...
Thanks, Jib.