1、需求分析
用winform窗体程序,开发一个能够自动、批量对图片进行缩放和裁剪的程序。
原本想直接从网上找类型的工具直接用,但是无奈现在网上能找到的工具,要么不能用,要么就是很
恶心的下载完后还有一堆插件的,要么就是我用不来的。
这个程序是我根据个人需求,想要把所有拍好的人像照,直接批处理成1寸的照片,就能省去很多裁剪图片的时间。
这里要对生成的1寸图片做个说明:1寸图片我网上查到的大小是:照片规格(英寸) (厘米) (像素)
1寸 2.5*3.5cm 413*295
由于在拍摄时可能存在横拍和竖拍,所以生成后图片虽然也是1寸的,但是方向不一样,这个不影响,还可以根据需求在代码中修改。
先看效果:
可以看出缩放图片后,图片的质量也会随之变低,而裁剪则不会有这个问题。
2、图片裁剪代码
1 /// <summary> 2 /// 裁剪按钮 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void Button1_Click(object sender, EventArgs e) 7 { 8 OpenFileDialog dialog = new OpenFileDialog(); //打开文件夹,选择图片 9 dialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif;*.JPG;*.PNG;|All files(*.*)|*.*"; 10 dialog.Multiselect = true; 11 if (dialog.ShowDialog() == DialogResult.OK) 12 { 13 string path = dialog.FileName; 14 Bitmap img = new Bitmap(path); 15 Image img2 = ImageTailor(img, 319, 449); //设置大小为1寸照片 16 string imgSaveUrl = @"D:/我的图片/处理完成/" + dialog.SafeFileName; //保存图片到文件夹 17 img2.Save(imgSaveUrl); 18 img2.Dispose(); //释放资源 19 } 20 } 21 22 public Image ImageTailor(Bitmap bmp,int nowWidth,int nowHeight) 23 { 24 Bitmap newbm = new Bitmap(nowWidth, nowHeight); 25 Graphics g = Graphics.FromImage(newbm); 26 g.InterpolationMode = InterpolationMode.HighQualityBicubic; 27 g.SmoothingMode = SmoothingMode.HighQuality; 28 g.CompositingQuality = CompositingQuality.HighQuality; 29 //前Rectangle代表画布大小,后Rectangle代表裁剪后右边留下的区域 30 g.DrawImage(bmp, new Rectangle(0, 0, nowWidth, nowHeight), new Rectangle(0, 0, bmp.Width / 2, bmp.Height), GraphicsUnit.Pixel); 31 g.Dispose(); 32 return newbm; 33 }
裁剪按钮方法还没完善好,目前只完成了单张图片的裁剪。要想修改成批量的,只需在openfiledialog控件设置成允许多选,然后根据选中的图片数量进行循环处理,就可以了。
后面的缩放按钮是比较完善的,可以允许多选图片,并进行批处理。
3、图片缩放代码:
缩放图片的代码看起来会比较复杂些,但是逻辑并不难。一些代码也是在网上看其他人写的,拿过来用(那个“中间件确实是自己写着玩的,懒得改回去,哈哈”)
1 /// <summary> 2 /// 显示图片 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void Button_SelectImg_Click(object sender, EventArgs e) 7 { 8 OpenFileDialog dialog = new OpenFileDialog(); 9 dialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif;*.JPG;*.PNG;|All files(*.*)|*.*"; 10 dialog.Multiselect = true; //允许文件多选 11 string folder = ""; 12 if (Directory.Exists(@"D:/我的图片/处理完成/")) 13 { 14 folder = @"D:/我的图片/处理完成/"; 15 } 16 else 17 { 18 Directory.CreateDirectory(@"D:/我的图片/处理完成/"); 19 folder = @"D:/我的图片/处理完成/"; 20 } 21 if (dialog.ShowDialog() == DialogResult.OK) 22 { 23 int fileCount = dialog.FileNames.Length; //获取选中图片数量 24 int countNum = fileCount; 25 for (int i = 0; i < fileCount; i++) 26 { 27 string path = dialog.FileNames[i]; //图片绝对路径,包含图片名称 28 Image img = GetReducedImage(path); 29 string imgSaveUrl = folder + dialog.SafeFileNames[i]; //保存图片到文件夹 30 img.Save(imgSaveUrl); 31 img.Dispose(); //释放资源 32 countNum--; 33 if (countNum == 0) 34 { 35 MessageBox.Show("处理图片完成,总计处理:" + fileCount + "张"); 36 } 37 }