Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Created October 11, 2017 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martyr2/a7db346e711198aa1d24a714387a6b7f to your computer and use it in GitHub Desktop.
Save Martyr2/a7db346e711198aa1d24a714387a6b7f to your computer and use it in GitHub Desktop.
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