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的截圖