具體啥的,我也不懂,就知道這樣是可以的。等有空了再研究吧。
功能是:裁剪圖片,但保持圖片原來的大小,被裁剪的區域用指定的顏色(白色)來填充,然后保存到另一個新的文件夾里,名稱不改變。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WFImg { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "請選擇文件路徑"; if (dialog.ShowDialog() == DialogResult.OK) { string foldPath = dialog.SelectedPath; this.textBox1.Text = foldPath; } } /// <summary> /// 剪裁 /// </summary> /// <param name="b">原始Bitmap</param> /// <param name="StartX">開始坐標X</param> /// <param name="StartY">開始坐標Y</param> /// <param name="iWidth">寬度</param> /// <param name="iHeight">高度</param> /// <returns>剪裁后的Bitmap</returns> public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight) { if (b == null) { return null; } int w = b.Width; int h = b.Height; if (StartX >= w || StartY >= h) { return null; } if (StartX + iWidth > w) { iWidth = w - StartX; } if (StartY + iHeight > h) { iHeight = h - StartY; } try { //Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);//裁剪成小一號的圖片 Bitmap bmpOut = new Bitmap(w, h, PixelFormat.Format24bppRgb);//保持原大小,裁剪部分用指定的顏色填充 Graphics graphics = Graphics.FromImage(bmpOut); graphics.Clear(Color.White);//裁剪部分用指定的顏色填充 graphics.DrawImage(b, new Rectangle(StartX, StartY, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel); graphics.Dispose(); return bmpOut; } catch { return null; } } private void button2_Click(object sender, EventArgs e) { int leftSize = Convert.ToInt32(txtLeft.Text); int topSize = Convert.ToInt32(txtTop.Text); int bottomSize = Convert.ToInt32(txtBottom.Text); int rightSize = Convert.ToInt32(txtRight.Text); string foldPath = textBox1.Text; string newPath = foldPath + "_new"; if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } //循環該目錄下的文件 DirectoryInfo dir = new DirectoryInfo(foldPath); FileInfo[] files = dir.GetFiles(); int fcount = files.Count(); if (fcount > 0) { for (int i = 0; i < fcount; i++) { FileInfo file = files[i]; Bitmap map = new Bitmap(file.FullName); int width = map.Width; int height = map.Height; map = KiCut(map, leftSize, topSize, width - rightSize - leftSize, height - bottomSize - topSize); map.Save(newPath + "\\" + file.Name); label6.Text = "執行結果:成功" +(i + 1) +"個"; } } } } }
界面就是這個鳥樣子:

上下左右都是像素值。
