1.效果图:
此效果图使用的选染色为Color.Yellow
![](https://images.cnblogs.com/cnblogs_com/a-toad/GDI/Colorize.JPG)
2.实现原理:
首先指定一种渲染颜色,然后计算当前象素的灰度值,用当前象素的灰度值分别乘以渲染色的R、G、B
分量值,将结果做为当前象素的最终颜色
3.实现代码:
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1
/// <summary>
2
/// 染色
3
/// </summary>
4
/// <param name="img">原始图像</param>
5
/// <param name="color">指定渲染色</param>
6
/// <returns></returns>
7
public static Image Colorize(Image img, Color color)
8
{
9
//初始化变量
10
Bitmap bmp = new Bitmap(img);
11
int width = img.Width;
12
int height = img.Height;
13![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
14
//获取Color对象的R、G、B分量值
15
byte red = color.R;
16
byte green = color.G;
17
byte blue = color.B;
18![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
19
//将Bitmap对象锁定到系统内存中
20
Rectangle rect = new Rectangle(0, 0, width, height);
21
ImageLockMode flag = ImageLockMode.ReadWrite;
22
PixelFormat format = PixelFormat.Format32bppArgb;
23
BitmapData data = bmp.LockBits(rect, flag, format);
24![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
25
//初始化一个byte类型的数组
26
int numBytes = width * height * 4;
27
byte[] rgbValues = new byte[numBytes];
28![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
29
//将非托管的内存指针复制到数组
30
IntPtr ptr = data.Scan0;
31
Marshal.Copy(ptr, rgbValues, 0, numBytes);
32![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
33
//修改每个象素R、G、B分量的值
34
int gray;
35
for (int i = 0; i < numBytes; i += 4)
36
{
37
//计算当前象素的灰度值
38
gray = (rgbValues[i] + rgbValues[i + 1] + rgbValues[i + 2]) / 3;
39![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
40
//染色后的R、G、B分量值
41
rgbValues[i] = (byte)(blue * gray / 255);
42
rgbValues[i+1] = (byte)(green * gray / 255);
43
rgbValues[i+2] = (byte)(red * gray / 255);
44
}
45![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
46
//将数组复制到非托管的内存指针
47
Marshal.Copy(rgbValues, 0, ptr, numBytes);
48![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
49
//从内存中解锁Bitmap
50
bmp.UnlockBits(data);
51![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
52
//返回值
53
return (Image)bmp;
54
}
4.说明:
计算灰度值可参考:图像处理:黑白效果(灰度处理)