在保持整体亮度的同时更改位图的色调

时间:2010-02-27 15:29:33

标签: c# .net bitmap rgb

我正在尝试编写一个函数,让我在保留图像整体亮度的同时对位图进行红移或蓝移。基本上,完全红移的位图将具有与原始相同的亮度,但是要彻底地红色(即,对于所有像素,G和B值将相等)。蓝色调相同(但R和G相等)。频谱偏移的程度需要在0到1之间变化。

提前致谢。

2 个答案:

答案 0 :(得分:4)

这是我正在寻找的效果(糟糕的JPEG,对不起):

alt text http://www.freeimagehosting.net/uploads/d15ff241ca.jpg

中间的图像是原始图像,侧面图像分别完全红移,部分红移,部分蓝移和全蓝移。

这是产生这种效果的函数:

public void RedBlueShift(Bitmap bmp, double factor)
{
    byte R = 0;
    byte G = 0;
    byte B = 0;
    byte Rmax = 0;
    byte Gmax = 0;
    byte Bmax = 0;
    double avg = 0;
    double normal = 0;
    if (factor > 1)
    {
        factor = 1;
    }
    else if (factor < -1)
    {
        factor = -1;
    }
    for (int x = 0; x < bmp.Width; x++)
    {
        for (int y = 0; y < bmp.Height; y++)
        {
            Color color = bmp.GetPixel(x, y);
            R = color.R;
            G = color.G;
            B = color.B;
            avg = (double)(R + G + B) / 3;
            normal = avg / 255.0; // to preserve overall intensity
            if (factor < 0) // red-tinted:
            {
                if (normal < .5)
                {
                    Rmax = (byte)((normal / .5) * 255);
                    Gmax = 0;
                    Bmax = 0;
                }
                else
                {
                    Rmax = 255;
                    Gmax = (byte)(((normal - .5) * 2) * 255);
                    Bmax = Gmax;
                }
                R = (byte)((double)R - ((double)(R - Rmax) * -factor));
                G = (byte)((double)G - ((double)(G - Gmax) * -factor));
                B = (byte)((double)B - ((double)(B - Bmax) * -factor));
            }
            else if (factor > 0) // blue-tinted:
            {
                if (normal < .5)
                {
                    Rmax = 0;
                    Gmax = 0;
                    Bmax = (byte)((normal / .5) * 255);
                }
                else
                {
                    Rmax = (byte)(((normal - .5) * 2) * 255);
                    Gmax = Rmax;
                    Bmax = 255;
                }
                R = (byte)((double)R - ((double)(R - Rmax) * factor));
                G = (byte)((double)G - ((double)(G - Gmax) * factor));
                B = (byte)((double)B - ((double)(B - Bmax) * factor));
            }
            color = Color.FromArgb(R, G, B);
            bmp.SetPixel(x, y, color);
        }
    }
}

答案 1 :(得分:3)

您可以使用ColorMatrix类。 this project中提供了一个很好的教程。