VB.NET
Public Shared Function CreateGrayscaleImage(ByVal img As Image) As Image
Dim newImg As New Bitmap(img.Width, img.Height)
Dim g As Graphics = Graphics.FromImage(newImg)
Dim cm As New System.Drawing.Imaging.ColorMatrix( _
New Single()() { _
New Single() {0.299F, 0.299F, 0.299F, 0, 0}, _
New Single() {0.587F, 0.587F, 0.587F, 0, 0}, _
New Single() {0.114F, 0.114F, 0.114F, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1} _
})
Dim ia As New System.Drawing.Imaging.ImageAttributes()
ia.SetColorMatrix(cm)
g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), _
0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia)
g.Dispose()
Return newImg
End Function
C#public static Image CreateGrayscaleImage(Image img)
{
Bitmap newImg = new Bitmap(img.Width, img.Height);
Graphics g = Graphics.FromImage(newImg);
System.Drawing.Imaging.ColorMatrix cm =
new System.Drawing.Imaging.ColorMatrix(
new float[][]{
new float[]{0.299f, 0.299f, 0.299f, 0 ,0},
new float[]{0.587f, 0.587f, 0.587f, 0, 0},
new float[]{0.114f, 0.114f, 0.114f, 0, 0},
new float[]{0, 0, 0, 1, 0},
new float[]{0, 0, 0, 0, 1}
});
System.Drawing.Imaging.ImageAttributes ia =
new System.Drawing.Imaging.ImageAttributes();
ia.SetColorMatrix(cm);
g.DrawImage(img,
new Rectangle(0, 0, img.Width, img.Height),
0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia);
g.Dispose();
return newImg;
}