C# 调整图像的亮度对比度和伽玛值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15408607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:43:31  来源:igfitidea点击:

Adjust brightness contrast and gamma of an image

c#.netimageimage-processingbrightness

提问by VladL

What is an easy way to adjust brightness contrast and gamma of an Image in .NET

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

Will post the answer myself to find it later.

将自己发布答案以供稍后查找。

采纳答案by VladL

c# and gdi+ have a simple way to control the colors that are drawn. It's basically a ColorMatrix. It's a 5×5 matrix that is applied to each color if it is set. Adjusting brightness is just performing a translate on the color data, and contrast is performing a scale on the color. Gamma is a whole different form of transform, but it's included in ImageAttributes which accepts the ColorMatrix.

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);