C# 影像處理(二)—— 黑白效果

來源:互聯網
上載者:User

 今天就說一下怎樣把一幅圖片做成黑白圖片的效果,就是把圖片黑白化。之前開啟圖片的方法已經發表了,具體地址是:

C# 影像處理(一)

 

   再面對一幅要處理成黑白效果的圖片,我為此寫了以下一個函數,

    /// <summary>
    /// 將圖片轉為為黑白圖片
    /// </summary>
    /// <param name="mybt">要進行處理的圖片</param>
    /// <param name="width">圖片的長度</param>
    /// <param name="height">圖片的高度</param>
    /// <returns>已經被處理後的黑白圖片</returns>
    public Bitmap BWPic(Bitmap mybm, int width, int height)
    {
        Bitmap bm = new Bitmap(width, height);//初始化一個Bitmap對象,用來記錄處理後的圖片
        int x, y, result;//x,y是迴圈次數,result是記錄處理後的像素值
        Color pixel;

        for (x = 0; x < width; x++)
        {
            for (y = 0; y < height; y++)
            {
                pixel = mybm.GetPixel(x, y);//擷取當前座標的像素值
                result = (pixel.R + pixel.G + pixel.B) / 3;//取紅綠藍三色的平均值

                //繪圖,把處理後的值賦值到剛才定義的bm對象裡面
                bm.SetPixel(x, y, Color.FromArgb(result, result, result));
            }
        }

        return bm;//返回黑白圖片
    }

    最後利用一個pictureBox控制項把處理後的圖片呈現出來,利用的是下面這個語句,

    int width = this.pictureBox.Width;//圖片容器的長度
    int height = this.pictureBox.Height;//圖片容器的寬度
    this.pictureBox.Image = pix.BWPic((Bitmap)this.pictureBox.Image, width, height);//處理圖片

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.