搜尋此網誌

2008年11月30日 星期日

C# 簡單一鍵影像灰階化

利用GetPixel與SetPixel達到簡易的圖片灰階化處理。

開啟圖檔

private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JPG(*.jpg)|*.jpg|" + "BMP(*.BMP)|*.bmp|" + "GIF(*.GIT)|*.gif|" + "所有檔案|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.Width = Image.FromFile(openFileDialog.FileName).Width;
pictureBox1.Height = Image.FromFile(openFileDialog.FileName).Height;
pictureBox1.Image = Image.FromFile(openFileDialog.FileName);
}
}























灰階化

private void btnGray_Click(object sender, EventArgs e)
{
//前提利用OpenFileDialog將影像放到pictureBox1
try
{
//並宣告bm1為Bitmap
Bitmap bm1 = (Bitmap)pictureBox1.Image;
//宣告寬及高
int w1 = pictureBox1.Image.Width;
int h1 = pictureBox1.Image.Width;
int x;
int y;
//掃影像每一個pixel並做處理
for (y = 0; y <= h1 - 1; y++)
{
for (x = 0; x <= w1 - 1; x++)
{
Color c1 = bm1.GetPixel(x, y);
int r1 = c1.R;
int g1 = c1.G;
int b1 = c1.B;
int avg1 = (r1 + g1 + b1) / 3;
bm1.SetPixel(x, y, Color.FromArgb(avg1, avg1,avg1));
}
}
//處理完後放回pictureBox1
pictureBox1.Image = bm1;
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}























Sample SourceCode:
Download



Reference:

日向俊二、陳亦苓 譯,”Visual Basic 2005 功能索引式參考手冊”

1 則留言:

  1. int h1 = pictureBox1.Image.Width;
    應該要改為
    int h1 = pictureBox1.Image.Height;

    回覆刪除