C# 仿照photoshop 亮度调节
时间: 2024-08-14 10:00:26 浏览: 57
C#调用photoshop工具源码
在C#中,如果你想要创建一个类似于Photoshop中的亮度调节功能,你可以利用.NET Framework中的System.Drawing命名空间,特别是Image类及其派生类。这里是一个简单的示例,展示如何调整图像的亮度:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
public class ImageBrightnessModifier {
public static Bitmap AdjustBrightness(Bitmap sourceImage, float brightnessFactor) {
if (sourceImage == null) throw new ArgumentNullException(nameof(sourceImage));
// 创建一个新的Bitmap,用于保存处理后的图像
Bitmap result = new Bitmap(sourceImage.Width, sourceImage.Height);
// 使用锁像素的方式进行操作,防止并发修改
using (Graphics graphics = Graphics.FromImage(result)) {
// 设置绘图上下文的模式
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(sourceImage, 0, 0, result.Width, result.Height);
// 获取图像的数据
ColorMatrix colorMatrix = new ColorMatrix(
new float[,]
{
{brightnessFactor, 0, 0, 0, 0},
{0, brightnessFactor, 0, 0, 0},
{0, 0, brightnessFactor, 0, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 1} // Alpha通道保持不变
});
// 应用矩阵变换
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
graphics.DrawImage(sourceImage, new Rectangle(0, 0, result.Width, result.Height), 0, 0, result.Width, result.Height, GraphicsUnit.Pixel, attributes);
}
return result;
}
}
// 调用示例
Bitmap originalImage = ...; // 加载图片
float brightnessLevel = 1.5f; // 调整范围从-1到1,正值增加亮度,负值降低亮度
Bitmap brightenedImage = ImageBrightnessModifier.AdjustBrightness(originalImage, brightnessLevel);
```
阅读全文