以下是“C#图像亮度调整的方法”的完整攻略,包含两个示例。
简介
在C#中,您可以使用System.Drawing.Imaging命名空间中的类来调整图像的亮度。本攻略将详细介绍如何使用C#调整图像的亮度,并提供两个示例。
示例1
以下是示例,演示了如何使用C#调整图像的亮度:
- 创建一个新的C#控制台应用程序。
- 在代码中,使用Bitmap类加载图像。以下是示例代码:
using System.Drawing;
Bitmap image = new Bitmap("image.jpg");
- 使用ColorMatrix类创建一个调整亮度的矩阵。以下是示例代码:
using System.Drawing;
using System.Drawing.Imaging;
float brightness = 0.5f; // 亮度值,范围从-1到1
ColorMatrix matrix = new ColorMatrix(new float[][] {
new float[] { brightness, 0, 0, 0, 0 },
new float[] { 0, brightness, 0, 0, 0 },
new float[] { 0, 0, brightness, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
});
- 使用ImageAttributes类将矩阵应用于图像。以下是示例代码:
using System.Drawing;
using System.Drawing.Imaging;
float brightness = 0.5f; // 亮度值,范围从-1到1
ColorMatrix matrix = new ColorMatrix(new float[][] {
new float[] { brightness, 0, 0, 0, 0 },
new float[] { 0, brightness, 0, 0, 0 },
new float[] { 0, 0, brightness, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix);
Graphics graphics = Graphics.FromImage(image);
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
- 运行程序,查看图像的亮度已更改。
示例2
以下是另一个示例,演示了如何使用C#调整图像的亮度并保存为新图像:
- 创建一个新的C#控制台应用程序。
- 在代码中,使用Bitmap类加载图像。以下是示例代码:
using System.Drawing;
Bitmap image = new Bitmap("image.jpg");
- 使用ColorMatrix类创建一个调整亮度的矩阵。以下是示例代码:
using System.Drawing;
using System.Drawing.Imaging;
float brightness = 0.5f; // 亮度值,范围从-1到1
ColorMatrix matrix = new ColorMatrix(new float[][] {
new float[] { brightness, 0, 0, 0, 0 },
new float[] { 0, brightness, 0, 0, 0 },
new float[] { 0, 0, brightness, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
});
- 使用ImageAttributes类将矩阵应用于图像,并保存为新图像。以下是示例代码:
using System.Drawing;
using System.Drawing.Imaging;
float brightness = 0.5f; // 亮度值,范围从-1到1
ColorMatrix matrix = new ColorMatrix(new float[][] {
new float[] { brightness, 0, 0, 0, 0 },
new float[] { 0, brightness, 0, 0, 0 },
new float[] { 0, 0, brightness, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix);
Bitmap newImage = new Bitmap(image.Width, image.Height);
Graphics graphics = Graphics.FromImage(newImage);
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
newImage.Save("newImage.jpg", ImageFormat.Jpeg);
- 运行程序,查看新图像的亮度已更改并保存。
结论
本攻略详细介绍了如何使用C#调整图像的亮度,并提供了两个示例,分别演示了如何调整图像的亮度和如何调整图像的亮度并保存为新图像。通过学习本攻略,您可以了解如何使用C#调整图像的亮度,并在需要时保存为新图像。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#图像亮度调整的方法 - Python技术站