24 กุมภาพันธ์ 2552

Image Processing ด้วย C# 1

Image Processing ด้วย C# 1



ในบทแรกนี้เราจะทำการเปิดไฟล์ภาพแล้วแสดงผล
เป้าหมาย



ขั้นตอน
สมมติว่าเราสร้างเมนูเรียบร้อยแล้ว

1. ประกาศตัวแปรสำหรับเก็บภาพ เป็นตัวแปรคลาส
private Bitmap bmp;

2. ในส่วนของเมนู Open ให้เพิ่มรหัสโปรแกรมดังนี้
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//Call open dialog
OpenFileDialog openFileDialog = new OpenFileDialog();
// Default Initial directory
openFileDialog.InitialDirectory = "c:\\";
// File type filter
openFileDialog.Filter = "Bitmap files (*.bmp)|*.bmp|Jpeg files (*.jpg)|*.jpg|PNG files (*.png)|*.png|All valid files (*.bmp/*.jpg/*.png)|*.bmp/*.jpg/*.png";
// Set png to be a default format
openFileDialog.FilterIndex = 3;
openFileDialog.RestoreDirectory = true;

// if click OK to open image
if (DialogResult.OK == openFileDialog.ShowDialog())
{
// Load bitmap from file
bmp = (Bitmap)Bitmap.FromFile(openFileDialog.FileName, false);
// set width and height of form, compensate for menubar
this.Width = bmp.Width + 5;
this.Height = bmp.Height + 55;
// invoke paint method
this.Invalidate();
}
}

3. เพิ่ม Event ชื่อ Paint ให้กับฟอร์ม
แล้วเพิ่มรหัสโปรแกรมดังนี้

private void Form1_Paint(object sender, PaintEventArgs e)
{
// if image file does not exist
if (bmp == null)
return;

// else draw image to form
Graphics g = e.Graphics;
Rectangle r = new Rectangle(0, 25, bmp.Width, bmp.Height);
g.DrawImage(bmp, r);
}

ไม่มีความคิดเห็น: