ColorMatrix用于部分灰度

时间:2012-06-09 20:01:21

标签: c# gdi+

所以我正在使用我在网络上发现的一些变体来将图像转换为灰度。我希望能够“淡出灰色”I.e.逐渐淡化颜色,这样我就可以从全彩色到部分彩色到纯灰色。

public static ColorMatrix ColorMatrixForGrayScale = new ColorMatrix(new[] {
                             new[] {.3f, .3f, .3f, 0, 0},
                             new[] {.59f, .59f, .59f, 0, 0},
                             new[] {.11f, .11f, .11f, 0, 0},
                             new float[] {0, 0, 0, 1, 0},
                             new float[] {0, 0, 0, 0, 1} });

    public static Bitmap MakeGrayscale(Image original, int percent = 100)
    {
        ColorMatrix matrix = GetMatrix(percent); // returns a variation of the above.

        //create a blank bitmap the same size as original
        var newBitmap = new Bitmap(original.Width, original.Height);

        //get a graphics object from the new image
        var g = System.Drawing.Graphics.FromImage(newBitmap);

        //create some image attributes
        var attributes = new ImageAttributes();

        //set the color matrix attribute
        attributes.SetColorMatrix(matrix);

        //draw the original image on the new image
        //using the grayscale color matrix
        g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
           0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

        //dispose the Graphics object
        g.Dispose();
        return newBitmap;
    }

所以问题是两部分。首先,我可以使用矩阵吗?如果是,我会改变什么,如果不是,什么是可行的方法?我正在考虑创建全灰度,然后将其与彩色图像合并(一些如何)。

由于

编辑:原始来源Switch on the code

1 个答案:

答案 0 :(得分:1)