The best way I can think of it to use the built-in ColorMatrix
class to change the Gamma and the Contrast of the image.
Here is a result for a Gamma = 6.27
and a Contrast = +1.04
:
Here is the code I used:
using System.Drawing.Imaging;
..
public static Bitmap ApplyGamma(Bitmap bmp0, float gamma, float contrast)
{
Bitmap bmp1 = new Bitmap(bmp0.Width, bmp0.Height);
using (Graphics g = Graphics.FromImage(bmp1))
{
ColorMatrix colorMatrix = new ColorMatrix(new float[][]
{
new float[] {contrast, 0, 0, 0, 0},
new float[] {0,contrast, 0, 0, 0},
new float[] {0, 0, contrast, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
attributes.SetGamma(gamma, ColorAdjustType.Bitmap);
g.DrawImage(bmp0, new Rectangle(0, 0, bmp0.Width, bmp0.Height),
0, 0, bmp0.Width, bmp0.Height, GraphicsUnit.Pixel, attributes);
}
return bmp1;
}
The function uses two variables and two TrackBars
along with two Labels
:
float gamma = 1f ;
float contrast = 1f;
private void trackBar1_Scroll(object sender, EventArgs e)
{
gamma = 1f * trackBar1.Value / 100f;
label1.Text = gamma.ToString("#0.00");
pictureBox1.Image = ApplyGamma(originalImage, gamma, contrast);
}
private void trackBar2_Scroll(object sender, EventArgs e)
{
contrast = 1f * trackBar2.Value / 1000f;
label2.Text = contrast.ToString("#0.00");
pictureBox1.Image = ApplyGamma(originalImage, gamma, contrast);
}
Note that I am leaking the Bitmaps; it is just for testing ;-)