调整图像的亮度、对比度和伽马值

18
在.NET中,有什么简单的方法可以调整图像的亮度、对比度和伽马值?
2个回答

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

嗨!我无法使用,如何使用原始图像和调整后的图像? - Paulo Fernando

0
借鉴VladL的回答,我们进一步探讨。
Bitmap originalImage = (Bitmap)myPictureBox.Image; // my application has a Winform with a PictureBox to display an image and is defined outside of this code block.
Bitmap adjustedImage = new Bitmap(myPictureBox.Image.Width, myPictureBox.Image.Height); // Created an instance of Bitmap with the same dimensions as myOriginalImage

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

// Now display the adjusted image in Winform PictureBox
myPictureBox.Image = adjustedImage;
this.Refresh();

根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接