Hi everyone I´m having problems with my code, I´m trying to extract the R,G,B value from an Image, I´m doing this
with the help of System.Runtime.InteropServices.Marshal.Copy, at first I create a pointer to the first
line of the Image, and then I copy all that row data to an array, after that I cover the array and safe the
R,G,B values into variables. The problem is, once I have finish covering the first row I change my pointer position
adding it an offset but, when I try to execute again this "System.Runtime.InteropServices.Marshal.Copy(realByteAddr, rgbValues, 0, bytes);"
I get the Next Error
" Access violation was unhandled " you are trying to read or write into protected memory.
Sometimes this means thatthe memory is damage.
So... any advice??? thank you very much
Here is the code:
static private void RGBextract(Bitmap bmp, out int rojo, out int verde, out int azul)
{
int r = 0, g = 0, b = 0;
int totales = 0;
// Lock the bitmap's bits.
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
int y = 0;
while (y < bmp.Height)
{
// Get the address of the first line.
int offset = (y * bmpData.Stride);
int ptr = bmpData.Scan0.ToInt32();
// Get address of next row
IntPtr realByteAddr = new IntPtr(ptr +System.Convert.ToInt32(y * bmpData.Stride));
// Declare an array to hold the bytes of the bitmap.
// This code is specific to a bitmap with 24 bits per pixels.
int bytes = bmp.Width * bmp.Height * 3;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(realByteAddr, rgbValues, 0, bytes); // Copy (source, destination,inicio,longitud)
// Set every red value to 255.
int counter = 0;
while (counter < bmp.Width)
{
b = b + rgbValues[counter];
counter++;
g = g + rgbValues[counter];
counter++;
r = r + rgbValues[counter];
counter++;
}
y++;
}
totales = bmp.Height * bmp.Width;
rojo = r/totales;
verde = g/totales;
azul = b/totales;
// Copy the RGB values back to the bitmap
//System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, realByteAddr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
}