Skip to content

Instantly share code, notes, and snippets.

@yatt
Created April 13, 2011 12:12
Show Gist options
  • Save yatt/917434 to your computer and use it in GitHub Desktop.
Save yatt/917434 to your computer and use it in GitHub Desktop.
extension method definition for converting image to grayscale
using System.Drawing;
using System.Drawing.Imaging;
namespace BitmapConversion
{
static class GrayScale
{
public static Bitmap Transform(Bitmap bmp, float[][] matrix)
{
ColorMatrix mat = new ColorMatrix(matrix);
ImageAttributes attr = new ImageAttributes();
attr.SetColorMatrix(mat);
int w = bmp.Width;
int h = bmp.Height;
Bitmap newbmp = new Bitmap(w, h);
using (Graphics graphics = Graphics.FromImage(newbmp))
{
Rectangle rect = new Rectangle(0, 0, w, h);
graphics.DrawImage(bmp, rect, 0, 0, w, h, GraphicsUnit.Pixel, attr);
}
return newbmp;
}
// (r + g + b) / 3
public static Bitmap SimpleGrayscale(this Bitmap bmp)
{
const float r = 0.333333F;
const float g = 0.333333F;
const float b = 0.333333F;
float[][] matrix = {
new float[]{r, r, r, 0, 0},
new float[]{g, g, g, 0, 0},
new float[]{b, b, b, 0, 0},
new float[]{0, 0, 0, 1, 0},
new float[]{0, 0, 0, 0, 1}
};
return Transform(bmp, matrix);
}
// 0.298912r + 0.586611g + 0.114478b
public static Bitmap NTSCWeightedAverage(this Bitmap bmp)
{
const float r = 0.298912F;
const float g = 0.586611F;
const float b = 0.114478F;
float[][] matrix = {
new float[]{r, r, r, 0, 0},
new float[]{g, g, g, 0, 0},
new float[]{b, b, b, 0, 0},
new float[]{0, 0, 0, 1, 0},
new float[]{0, 0, 0, 0, 1}
};
return Transform(bmp, matrix);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment