C#切割指定区域图片操作
使用winform制作了一个切割图片的功能,切一些固定大小的图片,比如头像。
界面如图:
打开本地图片
OpenFileDialog opdialog = new OpenFileDialog(); opdialog.InitialDirectory = @"C:\"; opdialog.FilterIndex = 1; opdialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG"; if (opdialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) this.pb_photo_original.Image = Image.FromFile(opdialog.FileName);
拖动选择切割区域
if (e.Button != MouseButtons.Left) return; if (oldCutRect.Contains(e.Location)) { this.newCutRect.Offset(e.Location.X - this.m_LastMSPoint.X, e.Location.Y - this.m_LastMSPoint.Y); if (newCutRect.Location.X < 0) newCutRect.X = 0; if (newCutRect.Location.Y < 0) newCutRect.Y = 0; if (newCutRect.Location.X + 128 > 300) newCutRect.X = 300 - 128; if (newCutRect.Location.Y + 160 > 300) newCutRect.Y = 300 - 160; this.panel_shade.Invalidate(oldCutRect, false); this.panel_shade.Invalidate(newCutRect, false); this.m_LastMSPoint = e.Location; oldCutRect = newCutRect; }
保存区域图片完成切割
Bitmap bitmap = new Bitmap(128, 160); //创建作图区域 Graphics graphic = Graphics.FromImage(bitmap); Point p = this.pb_photo_original.PointToScreen(this.oldCutRect.Location); //截取原图相应区域写入作图区 //graphic.DrawImage(this.pb_photo_original.Image, new Rectangle(0, 0, 128, 160), oldCutRect, GraphicsUnit.Pixel); graphic.CopyFromScreen(p.X, p.Y, 0, 0, new Size(128, 160)); Bitmap zoomBitmap = new Bitmap(bitmap, new Size(80, 100)); this.pb_photo_cut.Image = zoomBitmap; //保存图象 zoomBitmap.Save(@"D:\test.jpg"); bitmap.Dispose(); graphic.Dispose();