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的截图
补充:软件开发 , C# ,