如何将修改后的Bitmap从子窗体Form2传回主窗体Form1?
WinForms窗体间Bitmap回传解决方案
核心思路
- 在Form2中定义类级别的Bitmap字段保存修改后的图像
- 给Form2添加公共属性供Form1读取修改后的Bitmap
- 利用
ShowDialog()的返回值区分用户确认/取消操作,仅在确认时读取返回图像
修改后的Form2代码
// 类级别字段,保存修改后的Bitmap private Bitmap _modifiedBitmap; // 公共属性,供Form1获取修改后的图像 public Bitmap ModifiedBitmap => _modifiedBitmap; int integer_f2; internal void ReceiveData(int integer) { integer_f2 = integer; } public void Linear(Bitmap bmp) { // 创建修改后的Bitmap实例 _modifiedBitmap = new Bitmap(bmp.Width, bmp.Height); for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color clr = Color.FromArgb(255, integer_f2, integer_f2, integer_f2); _modifiedBitmap.SetPixel(x, y, clr); } } // 可选:在Form2中显示修改后的图像(需先在Form2添加PictureBox控件,命名为pictureBox1) pictureBox1.Image = _modifiedBitmap; } private void Button_Cancel_2_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void Button_OK_2_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); }
修改后的Form1代码
private void Button1_Click(object sender, EventArgs e) { using (Form2 f2 = new Form2()) { f2.ReceiveData(integer); f2.Linear(bmp); DialogResult result = f2.ShowDialog(); if (result == DialogResult.OK) { // 获取修改后的Bitmap并处理 Bitmap modifiedBmp = f2.ModifiedBitmap; // 示例:显示在Form1的PictureBox中 // pictureBox1.Image = modifiedBmp; } } }
注意事项
- Bitmap属于非托管资源,使用完毕后需调用
Dispose()释放内存,使用using语句包裹Form2实例可确保资源自动释放 - 若直接修改传入的Bitmap实例,会直接改变原对象状态,创建新实例的方式更安全,避免影响原图像
- Form2中若要预览修改后的图像,需添加PictureBox控件并将
_modifiedBitmap赋值给其Image属性
内容的提问来源于stack exchange,提问作者Gaunter O'Dimm
相关产品推荐
相关产品推荐

