如何使用跟踪栏降低图像亮度?



我只能使用跟踪栏增加亮度。即使我把它拉到后面,亮度也会不断增加。

有人可以帮忙吗?

Bitmap newbitmap;
private void brightnessBar_Scroll(object sender, EventArgs e)
{
brightnessLabel.Text = brightnessBar.Value.ToString();
newbitmap = (Bitmap)boxPic.Image;
boxPic.Image = AdjustBrightness(newbitmap, brightnessBar.Value);
}
public static Bitmap AdjustBrightness(Bitmap Image, int Value)
{
Bitmap TempBitmap = Image;
float FinalValue = (float)Value / 255.0f;
Bitmap NewBitmap = new Bitmap(TempBitmap.Width, TempBitmap.Height);
Graphics NewGraphics = Graphics.FromImage(NewBitmap);
float[][] FloatColorMatrix ={
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {FinalValue, FinalValue, FinalValue, 1, 1}
};
ColorMatrix NewColorMatrix = new ColorMatrix(FloatColorMatrix);
ImageAttributes Attributes = new ImageAttributes();
Attributes.SetColorMatrix(NewColorMatrix);
NewGraphics.DrawImage(TempBitmap,
new Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height),
0, 0, TempBitmap.Width, TempBitmap.Height,GraphicsUnit.Pixel, Attributes);
Attributes.Dispose();
NewGraphics.Dispose();
return NewBitmap;
}

您的代码有两个问题。 首先是你正在改变你的图像并替换你的原始图像。 因此,每次您进行更改时,它都会在您之前的所有更改之上添加。 您需要将原始图像保存在某个地方,并将其用作更改的基础。

Bitmap origbitmap= null;
private void brightnessBar_Scroll(object sender, EventArgs e)
{
//we only capture the "original" bitmap once, at the start of the operation
//and then we hold on to it to apply all future edits against the original
if (origbitmap== null)
origbitmap= (Bitmap)boxPic.Image;
brightnessLabel.Text = brightnessBar.Value.ToString();
boxPic.Image = AdjustBrightness(origbitmap, brightnessBar.Value);
}

第二个问题是,您正在将更改应用于 ColorMatrix 的"W"组件。 关于ColorMatrix的文档不是那么好(https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imaging.colormatrix?view=netframework-4.7.2)

但是,W 分量似乎是平移,这意味着它是颜色通道的直接添加。 所以你的运算结果是 R = R + W, G = G + W, B = B + W, A = A + W。 你想要的可能是一个标量操作;

float[][] FloatColorMatrix ={
new float[] {FinalValue, 0, 0, 0, 0},
new float[] {0, FinalValue, 0, 0, 0},
new float[] {0, 0, FinalValue, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
};

FinalValue(来自您的跟踪栏)是原始颜色的乘数。 从技术上讲,这不会是真正的"亮度"调整(您需要为此研究颜色空间转换),但这将是线性改变每个颜色通道强度的非常简单的方法。

顺便说一句,如果您的跟踪栏限制为 255,您的最终值将永远不会超过 1,并且您的图像亮度永远不会增加。 如果您的跟踪栏上升到 512,FinalValue 可能会达到 2 倍(中间为 1 倍),因此您可以以每通道 2 倍的强度达到最大值。