Bitmap curBitmap = new Bitmap("c:\\6.jpg");
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 = bmpData.Stride * bmpData.Width;//获取或设置 Bitmap 对象的跨距宽度
Console.WriteLine(bytes);
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
double colorTemp = 0;
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 0; j < bmpData.Width * 3; j += 3)
{
colorTemp=grayValues[i * bmpData.Stride +j+2]*0.299 + grayValues[i * bmpData.Stride +j+1]*0.587+grayValues[i * bmpData.Stride +j]*0.114;
grayValues[i * bmpData.Stride + j + 2] = grayValues[i * bmpData.Stride + j + 1] = grayValues[i * bmpData.Stride + j] = (Byte)colorTemp;
}
}以上的语句是将图片灰度化 System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
curBitmap.UnlockBits(bmpData);
curBitmap.Save("c:\\灰度化结果1.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
这样运行是可以的但是我在这两段代码中加入 这样一段代码 就会报出这样的错误! 新建一个数组都不行吗?
byte[] TwoValues = new byte[bytes];
TwoValues = grayValues;
for (int i = 0; i < bytes; i++)
{
if (TwoValues[i] <201)
TwoValues[i] = 0;
else
TwoValues[i] = 255;
}
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 = bmpData.Stride * bmpData.Width;//获取或设置 Bitmap 对象的跨距宽度
Console.WriteLine(bytes);
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
double colorTemp = 0;
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 0; j < bmpData.Width * 3; j += 3)
{
colorTemp=grayValues[i * bmpData.Stride +j+2]*0.299 + grayValues[i * bmpData.Stride +j+1]*0.587+grayValues[i * bmpData.Stride +j]*0.114;
grayValues[i * bmpData.Stride + j + 2] = grayValues[i * bmpData.Stride + j + 1] = grayValues[i * bmpData.Stride + j] = (Byte)colorTemp;
}
}以上的语句是将图片灰度化 System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
curBitmap.UnlockBits(bmpData);
curBitmap.Save("c:\\灰度化结果1.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
这样运行是可以的但是我在这两段代码中加入 这样一段代码 就会报出这样的错误! 新建一个数组都不行吗?
byte[] TwoValues = new byte[bytes];
TwoValues = grayValues;
for (int i = 0; i < bytes; i++)
{
if (TwoValues[i] <201)
TwoValues[i] = 0;
else
TwoValues[i] = 255;
}
看来我走到了一条很少有人走的路!
不过看在就你回复了我的帖子的份上!分都给你吧!哈哈!