您的位置:首页 > 编程语言 > C#

C#图片处理之:亮度和对比度的校正

2012-01-17 13:58 239 查看
亮度和对比度应该是最常见的处理要求了。就算是N年前9寸黑白电视机也必有这两个旋钮。

亮度调整算法很简单。对每一个像素的RGB值同时加上或减去一个特定的值就可以了。当然由于RGB取值范围都是在[0,255]的,所以要考虑到越界的问题。

public static Bitmap KiLighten(Bitmap b, int degree)
public static Bitmap KiContrast(Bitmap b, int degree)
...{


if (b == null)




...{


return null;


}




if (degree < -100) degree = -100;


if (degree > 100) degree = 100;




try




...{




double pixel = 0;


double contrast = (100.0 + degree) / 100.0;


contrast *= contrast;


int width = b.Width;


int height = b.Height;


BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);


unsafe




...{


byte* p = (byte*)data.Scan0;


int offset = data.Stride - width * 3;


for (int y = 0; y < height; y++)




...{


for (int x = 0; x < width; x++)




...{


// 处理指定位置像素的对比度


for (int i = 0; i < 3; i++)




...{


pixel = ((p[i] / 255.0 - 0.5) * contrast + 0.5) * 255;


if (pixel < 0) pixel = 0;


if (pixel > 255) pixel = 255;


p[i] = (byte)pixel;


} // i


p += 3;


} // x


p += offset;


} // y


}


b.UnlockBits(data);


return b;


}


catch




...{


return null;


}


} // end of Contrast
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: