温馨提示×

怎么动态更改PictureBox图片的亮度、对比度或饱和度

小亿
82
2024-05-27 10:44:13
栏目: 编程语言

要动态更改PictureBox图片的亮度、对比度或饱和度,可以使用以下步骤:

  1. 将PictureBox中的图片转换为Bitmap格式:
Bitmap bitmap = new Bitmap(pictureBox1.Image);
  1. 创建一个新的Bitmap对象来存储修改后的图片:
Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
  1. 定义需要修改的亮度、对比度和饱和度值:
float brightness = 0.1f; //亮度
float contrast = 1.5f; //对比度
float saturation = 1.5f; //饱和度
  1. 使用Graphics对象将原始图片绘制到新的Bitmap对象上,并在绘制时应用亮度、对比度和饱和度调整:
using (Graphics g = Graphics.FromImage(newBitmap))
{
    ImageAttributes attributes = new ImageAttributes();

    //亮度调整
    float[][] colorMatrixElements = {
        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[] {brightness, brightness, brightness, 0, 1}
    };
    ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
    attributes.SetColorMatrix(colorMatrix);

    //对比度调整
    g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, attributes);

    //饱和度调整
    ImageAttributes saturationAttributes = new ImageAttributes();
    saturationAttributes.SetColorMatrix(new ColorMatrix
    {
        Matrix33 = saturation
    });

    g.DrawImage(newBitmap, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height), 0, 0, newBitmap.Width, newBitmap.Height, GraphicsUnit.Pixel, saturationAttributes);
}
  1. 将修改后的图片显示在PictureBox中:
pictureBox1.Image = newBitmap;

通过以上步骤,可以动态更改PictureBox中图片的亮度、对比度和饱和度。您可以根据需要调整brightness、contrast和saturation的值来实现不同的效果。

0