You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#和SkiaSharp实现图像对比度调整

使用C# + SkiaSharp实现图像对比度调整

SkiaSharp的SKColorMatrix类没有直接提供C++中SkColorMatrix::setContrast对应的方法,我们可以手动实现对比度的矩阵计算逻辑,再构建颜色滤镜完成需求。

步骤1:实现对比度矩阵计算

参考Skia原生代码的对比度计算逻辑,转换成C#方法:

public static void SetContrast(SKColorMatrix matrix, float contrast)
{
    float scale = contrast + 1.0f;
    float translate = (-0.5f * scale) + 0.5f;

    // 重置矩阵为单位矩阵
    matrix.SetIdentity();
    
    // 调整RGB通道的缩放与偏移(Alpha通道保持不变)
    matrix.Scale(scale, scale, scale, 1.0f);
    matrix.Translate(translate, translate, translate, 0.0f);
}

步骤2:构建颜色滤镜并应用

按照C++代码的逻辑,创建矩阵、调整对比度、生成颜色滤镜,最终应用到图像:

// 初始化颜色矩阵
var colorMatrix = new SKColorMatrix();

// 设置对比度值(0.0=全灰,1.0=原始对比度,>1.0=提升对比度)
float contrastValue = 1.5f;
SetContrast(colorMatrix, contrastValue);

// 创建对应的颜色滤镜
using var colorFilter = SKColorFilter.CreateColorMatrix(colorMatrix);

// 示例:将滤镜应用到图像并保存
using var originalBitmap = SKBitmap.Decode("input.png");
using var outputBitmap = new SKBitmap(originalBitmap.Width, originalBitmap.Height);
using var canvas = new SKCanvas(outputBitmap);
using var paint = new SKPaint { ColorFilter = colorFilter };

canvas.DrawBitmap(originalBitmap, 0, 0, paint);

// 导出处理后的图像
using var image = SKImage.FromBitmap(outputBitmap);
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
using var stream = File.OpenWrite("output.png");
data.SaveTo(stream);

参数说明

  • 对比度参数范围和C++版本完全一致:
    • 0.0:图像完全变为灰色
    • 1.0:保留图像原始对比度
    • 大于1.0:提升图像对比度;介于0和1之间:降低图像对比度

内容的提问来源于stack exchange,提问作者Marcelo Janazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:07:37