將彩色照片轉為黑白照片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 轉黑白照片
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = @"D:\MyPhoto\";
if (open.ShowDialog() == DialogResult.OK)
{
ImageForm MyImage = new ImageForm(open.FileName);
MyImage.Show();
}
}
class ImageForm : Form
{
Image image;
public ImageForm(String Filename)
{
image = Image.FromFile(Filename);
this.Text = Filename;
int[,,] rgb =getRGBData();
doGray(rgb);
}
protected override void OnPaint(PaintEventArgs e)
{
this.Height = image.Height;
this.Width = image.Width;
e.Graphics.DrawImage(image, 0, 0,Width,Height);
}
public int[, ,] getRGBData()
{
//step1:利用bitmap將image包起來
Bitmap bimage = new Bitmap(image);
int Height = bimage.Height;
int Width = bimage.Width;
int[, ,] rgbData = new int[Width, Height, 3];
//step2:取得像點顏色資訊
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
Color color = bimage.GetPixel(x, y);
rgbData[x, y, 0] = color.R;
rgbData[x, y, 1] = color.G;
rgbData[x, y, 2] = color.B;
}
}
return rgbData;
}
public void doGray(int[, ,] rgbData)
{ //step1:建立bitmap元件
Bitmap bimage = new Bitmap(image);
int Height = bimage.Height;
int Width = bimage.Width;
//step2:設定像點資料
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
int gray = (rgbData[x, y, 0] + rgbData[x, y, 1] + rgbData[x, y, 2]) / 3;
bimage.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
}
}
//step3:更新顯示影像
image = bimage;
this.Refresh();
}
}
}
}
沒有留言:
張貼留言