彩色图转换为灰度图公式很简单:
Y=0.3RED+0.59GREEN+0.11 Blue
用GDI+实现的方式由两种:
1. 直接用上述公式修改象素点
2. 用ColorMatrix。
下面是用ColorMatrix实现示例:
using namespace Gdiplus;
Image img(wszFileName);
Graphics graphics(GetDC()->GetSafeHdc());
ColorMatrix cm= {0.3f, 0.3f, 0.3f, 0, 0,
0.59f,0.59f,0.59f,0, 0,
0.11f,0.11f,0.11f,0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1};
ImageAttributes ia;
ia.SetColorMatrix(&cm);

float x = (float)img.GetWidth();
float y = (float)img.GetHeight();
graphics.DrawImage(&img,
RectF(0.0f,0.0f,x,y,
0.0f,0.0f,x,y,
UnitPixel,
&ia);
遍历像素点,修改颜色,貌似比上面方法快
public static bool Invert0(Bitmap b)
{
BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
unsafe
{
byte * p = (byte *)(void *)Scan0;
int nOffset = stride - b.Width*3;
int nWidth = b.Width * 3;
int h=b.Height;
for(int y=0;y<h;++y)
{
for(int x=0; x < nWidth; ++x )
{
p[0] = (byte)(255-p[0]);
++p;
}
p += nOffset;
}
}
b.UnlockBits(bmData);
return true;
}
Y=0.3RED+0.59GREEN+0.11 Blue
用GDI+实现的方式由两种:
1. 直接用上述公式修改象素点
2. 用ColorMatrix。
下面是用ColorMatrix实现示例:


















遍历像素点,修改颜色,貌似比上面方法快
public static bool Invert0(Bitmap b)
{
BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
unsafe
{
byte * p = (byte *)(void *)Scan0;
int nOffset = stride - b.Width*3;
int nWidth = b.Width * 3;
int h=b.Height;
for(int y=0;y<h;++y)
{
for(int x=0; x < nWidth; ++x )
{
p[0] = (byte)(255-p[0]);
++p;
}
p += nOffset;
}
}
b.UnlockBits(bmData);
return true;
}