標籤:style class blog code http tar
1.:
此使用的選染色為Color.Yellow
2.實現原理:
首先指定一種渲染顏色,然後計算當前象素的灰階值,用當前象素的灰階值分別乘以渲染色的R、G、B
分量值,將結果做為當前象素的最終顏色
3.實現代碼:
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
14 //擷取Color對象的R、G、B分量值
15 byte red = color.R;
16 byte green = color.G;
17 byte blue = color.B;
18
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
25 //初始化一個byte類型的數組
26 int numBytes = width * height * 4;
27 byte[] rgbValues = new byte[numBytes];
28
29 //將非託管的記憶體指標複製到數組
30 IntPtr ptr = data.Scan0;
31 Marshal.Copy(ptr, rgbValues, 0, numBytes);
32
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
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
46 //將數組複製到非託管的記憶體指標
47 Marshal.Copy(rgbValues, 0, ptr, numBytes);
48
49 //從記憶體中解鎖Bitmap
50 bmp.UnlockBits(data);
51
52 //傳回值
53 return (Image)bmp;
54 }
4.說明:
計算灰階值可參考:影像處理:黑白效果(灰階處理)