C# 擷取影象中的特定區域
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;
using System.Drawing.Imaging;
namespace CutPicture
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//載入圖片
private void loadSrcBtn_Click(object sender, EventArgs e)
{
OpenFileDialog srcImageName = new OpenFileDialog();
if (srcImageName.ShowDialog() == DialogResult.OK)
{
Bitmap bmp = new Bitmap(Image.FromFile(srcImageName.FileName));
SrcImage.Image = bmp;
}
}
//擷取圖片 主要操作區域
private void cutImage(Point pos,int cutWidth, int cutHeight)
{
//先初始化一個位圖物件,來儲存擷取後的影象
Bitmap bmpDest = new Bitmap(cutWidth, cutHeight, PixelFormat.Format32bppRgb);
//這個矩形定義了,你將要在被擷取的影象上要擷取的影象區域的左頂點位置和擷取的大小
Rectangle rectSource = new Rectangle(pos.X, pos.Y, cutWidth, cutHeight);
//這個矩形定義了,你將要把 擷取的影象區域 繪製到初始化的點陣圖的位置和大小
//我的定義,說明,我將把擷取的區域,從點陣圖左頂點開始繪製,繪製擷取的區域原來大小
Rectangle rectDest = new Rectangle(0, 0, cutWidth, cutHeight);
//第一個引數就是載入你要擷取的影象物件,第二個和第三個引數及如上所說定義擷取和繪製圖像過程中的相關屬性,第四個屬性定義了屬性值所使用的度量單位
g.DrawImage(SrcImage.Image, rectDest, rectSource, GraphicsUnit.Pixel);
//這是在GUI上顯示被擷取的影象
cutedImage.Image = (Image)bmpDest;
g.Dispose();
}
//儲存擷取的圖片
private void saveCutImage_Click(object sender, EventArgs e)
{
SaveFileDialog saveImageName = new SaveFileDialog();
if (saveImageName.ShowDialog() == DialogResult.OK)
{
cutedImage.Image.Save(saveImageName.FileName);
}
}
//顯示擷取圖片
private void showCutImageBtn_Click(object sender, EventArgs e)
{
Point pos = new Point(0, 0);
if (!(posX.Text == "" || posY.Text == ""))
{
pos.X = int.Parse(posX.Text);
pos.Y = int.Parse(posY.Text);
}
int cutWidth, cutHeight;
cutWidth = 20;
cutHeight = 20;
if (!(cutImageWidth.Text == "" || cutImageHeight.Text == ""))
{
cutWidth = int.Parse(cutImageWidth.Text);
cutHeight = int.Parse(cutImageHeight.Text);
}
this.cutImage(pos, cutWidth, cutHeight);
}
}
}
下面是demo的截圖