调整图像的亮度对比度和灰度系数

Vla*_*adL 13 .net c# image image-processing brightness

什么是在.NET中调整图像的亮度对比度和灰度系数的简单方法

将自己发布答案以便稍后找到它.

Vla*_*adL 28

c#和gdi +有一种简单的方法来控制绘制的颜色.它基本上是一个ColorMatrix.它是一个5×5矩阵,如果设置,则应用于每种颜色.调整亮度只是对颜色数据进行转换,对比度在颜色上执行缩放.Gamma是一种完全不同的变换形式,但它包含在接受ColorMatrix的ImageAttributes中.

Bitmap originalImage;
Bitmap adjustedImage;
float brightness = 1.0f; // no change in brightness
float contrast = 2.0f; // twice the contrast
float gamma = 1.0f; // no change in gamma

float adjustedBrightness = brightness - 1.0f;
// create matrix that will brighten and contrast the image
float[][] ptsArray ={
        new float[] {contrast, 0, 0, 0, 0}, // scale red
        new float[] {0, contrast, 0, 0, 0}, // scale green
        new float[] {0, 0, contrast, 0, 0}, // scale blue
        new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha
        new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};

ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.ClearColorMatrix();
imageAttributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap);
Graphics g = Graphics.FromImage(adjustedImage);
g.DrawImage(originalImage, new Rectangle(0,0,adjustedImage.Width,adjustedImage.Height)
    ,0,0,originalImage.Width,originalImage.Height,
    GraphicsUnit.Pixel, imageAttributes);
Run Code Online (Sandbox Code Playgroud)