.net自带的截图功能,输入坐标和图片高度和宽度实现截图
winform形式
代码如下
```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CutImageTest
{
public partial class Form1 : Form
{
private object openFileDialog1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string imagePath = @"D:\job\A_PDF_TEST\ToBmp-img-1.bmp";
int x = int.Parse(locate_X_Box.Text);
int y = int.Parse(locate_Y_Box.Text);
int width = int.Parse(cut_Width_Box.Text);
int height = int.Parse(cut_Height_Box.Text);
cutPicture(imagePath, x, y, width, height);
}
public static void cutPicture(String picPath, int x, int y, int width, int height)
{
String oldPath = picPath;
String newPath = Path.GetExtension(oldPath);
newPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + "_new" + newPath;
Rectangle cropArea = new Rectangle(x, y, width, height);
Image img = Image.FromStream(new MemoryStream(File.ReadAllBytes(oldPath)));
if ((img.Width < x + width) || img.Height < y + height)
{
MessageBox.Show("裁剪尺寸超出原有尺寸!");
img.Dispose();
return;
}
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
bmpCrop.Save(newPath);
img.Dispose();
bmpCrop.Dispose();
}
}
}