Marshal.Copy地方出现“//尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”的错误
金池夜雨 2012-09-29 10:33:18 Bitmap curBitmap;
当我打开一封图像,执行下面的click事件后可以运行,但是当再次执行时就会在System.Runtime.InteropServices.Marshal.Copy地方出现“//尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”的错误,请教如何解决。
private void tranSpace_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
colorSpace clS = new colorSpace();
if (clS.ShowDialog() == DialogResult.OK)
{
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = curBitmap.Width * curBitmap.Height;
byte[] rgbValues = new byte[bytes * 3];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes * 3);
curBitmap.UnlockBits(bmpData);
byte colorCom = clS.GetCom;
byte[] grayValues = new byte[bytes];
byte tempB;
double tempD;
switch (colorCom)
{
case 0://red
for (int i = 0; i < bytes; i++)
grayValues[i] = rgbValues[i * 3 + 2];
break;
case 1://green
for (int i = 0; i < bytes; i++)
grayValues[i] = rgbValues[i * 3 + 1];
break;
case 2://blue;
for (int i = 0; i < bytes; i++)
grayValues[i] = rgbValues[i * 3];
break;
case 3://hue
double theta;
for (int i = 0; i < bytes; i++)
{
theta = Math.Acos(0.5 * ((rgbValues[i * 3 + 2] - rgbValues[i * 3 + 1]) + (rgbValues[i * 3 + 2] - rgbValues[i * 3])) / Math.Sqrt((rgbValues[i * 3 + 2] - rgbValues[i * 3 + 1]) * (rgbValues[i * 3 + 2] - rgbValues[i * 3 + 1]) + (rgbValues[i * 3 + 2] - rgbValues[i * 3]) * (rgbValues[i * 3 + 1] - rgbValues[i * 3]) + 0.0000000001)) / (2 * Math.PI);
tempD = (rgbValues[i * 3] <= rgbValues[i * 3 + 1]) ? theta : (1 - theta);
grayValues[i] = (byte)(tempD * 255);
}
break;
case 4://saturation
for (int i = 0; i < bytes; i++)
{
tempB = Math.Min(rgbValues[i * 3 + 2], rgbValues[i * 3 + 1]);
tempB = Math.Min(tempB, rgbValues[i * 3]);
tempD = 1.0 - 3.0 * tempB / (rgbValues[i * 3 + 2] + rgbValues[i * 3 + 1] + rgbValues[i * 3] + 0.0000000001);
grayValues[i] = (byte)(tempD * 255);
}
break;
case 5://intensity
for (int i = 0; i < bytes; i++)
grayValues[i] = (byte)((rgbValues[i * 3] + rgbValues[i * 3 + 1] + rgbValues[i * 3 + 2]) / 3);
break;
default:
break;
}
curBitmap = new Bitmap(curBitmap.Width, curBitmap.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
System.Drawing.Imaging.ColorPalette cp = curBitmap.Palette;
for (int i = 0; i < 256; i++)
{
cp.Entries[i] = Color.FromArgb(i, i, i);
}
curBitmap.Palette = cp;
bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
ptr = bmpData.Scan0;
System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
curBitmap.UnlockBits(bmpData);
Invalidate();
}
}
}
private void chCom_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
changeCom adjCom = new changeCom(this);
adjustCom(255,0,0,0);
adjCom.Show();
}
}