[英]How to decrease brightness on image using TrackBar?
我只能使用軌跡欄增加亮度。 即使我把它向后拉,亮度也會不斷增加。
有人可以幫忙嗎?
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://docs.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
(來自您的FinalValue
)是原始顏色的乘數。 這在技術上並不是真正的“亮度”調整(你會想要研究色彩空間變換),但這將是一種線性改變每個顏色通道強度的非常簡單的方法。
順便說一句,如果您的軌跡欄限制為255,您的FinalValue將永遠不會超過1,並且您的圖像的亮度永遠不會增加。 如果您的軌跡欄達到512,則FinalValue可以達到2x(中間值為1x),因此每個通道的最大強度為2x。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.