Skip to content

Instantly share code, notes, and snippets.

@Martyr2

Martyr2/grayscale.cs

Created Oct 11, 2017
Embed
What would you like to do?
Grayscale an image (in other words make it black and white)
/// <summary>
/// Grayscales an image
/// </summary>
/// <param name="source">Source image to grayscale</param>
/// <returns>New grayscaled image</returns>
private Image grayScale(ref Image source) {
Bitmap bitMap = new Bitmap(source);
using (Graphics g = Graphics.FromImage(bitMap)) {
System.Drawing.Imaging.ColorMatrix matrix = new System.Drawing.Imaging.ColorMatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
System.Drawing.Imaging.ImageAttributes attributes = new System.Drawing.Imaging.ImageAttributes();
attributes.SetColorMatrix(matrix);
g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
}
return (Image)bitMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.