影像處理---染色

來源:互聯網
上載者:User

標籤: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.說明:
         計算灰階值可參考:影像處理:黑白效果(灰階處理)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.