WinForm如何将选中的矩形区域保存为BMP或JPEG格式图片
WinForm选中矩形区域保存为图片实现方案
首先需要在代码顶部引入图片处理相关命名空间:using System.Drawing.Imaging;
核心实现逻辑
你只需要在Form1_MouseUp事件中补充如下代码即可完成保存功能,代码默认会擦掉蓝色选框再截图,避免选框被保存到最终图片里,也支持选择保存为BMP或JPEG格式:
private void Form1_MouseUp(object sender, MouseEventArgs e) { // 过滤宽高小于等于0的无效选区 if (mRect.Width <= 0 || mRect.Height <= 0) return; // 临时存储当前选区,先清空原选区刷新窗体擦掉蓝色选框 Rectangle tempSaveRect = mRect; mRect = Rectangle.Empty; this.Invalidate(); Application.DoEvents(); // 创建和选区大小一致的空位图 using (Bitmap targetBmp = new Bitmap(tempSaveRect.Width, tempSaveRect.Height)) { using (Graphics g = Graphics.FromImage(targetBmp)) { // 将窗体客户区坐标转换为屏幕坐标 Point screenStartPos = this.PointToScreen(new Point(tempSaveRect.X, tempSaveRect.Y)); // 拷贝屏幕对应区域的画面到位图 g.CopyFromScreen(screenStartPos, Point.Empty, tempSaveRect.Size); } // 弹出保存对话框让用户选择保存路径和格式 using (SaveFileDialog saveDialog = new SaveFileDialog()) { saveDialog.Filter = "BMP格式图片|*.bmp|JPEG格式图片|*.jpg;*.jpeg"; saveDialog.DefaultExt = "bmp"; if (saveDialog.ShowDialog() == DialogResult.OK) { ImageFormat saveFormat = saveDialog.FilterIndex == 1 ? ImageFormat.Bmp : ImageFormat.Jpeg; targetBmp.Save(saveDialog.FileName, saveFormat); MessageBox.Show("图片保存成功"); } } } // 如果需要保存后仍然显示蓝色选框,保留下面两行代码,不需要可删除 mRect = tempSaveRect; this.Invalidate(); }
注意事项
- 如果你的选区包含窗体上的其他控件,控件内容也会被一同保存到图片中
- 如果不需要用户手动选择保存路径,可以直接指定固定路径调用
targetBmp.Save("C:\\test.jpg", ImageFormat.Jpeg)即可
内容的提问来源于stack exchange,提问作者Usman Waheed
相关产品推荐
相关产品推荐

