如何保存PictureBox上创建的图形?

在c#和Visual Studio Windows窗体中,我已将图像加载到图片框(pictureBox2)中,然后将其裁剪并显示在另一个图片框(pictureBox3)中。

现在我想将pictureBox3中的内容保存为图像文件。

我怎样才能做到这一点?

private void crop_bttn_Click(object sender, EventArgs e) { Image crop = GetCopyImage("grayScale.jpg"); pictureBox2.Image = crop; Bitmap sourceBitmap = new Bitmap(pictureBox2.Image, pictureBox2.Width, pictureBox2.Height); Graphics g = pictureBox3.CreateGraphics(); g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel); sourceBitmap.Dispose(); } 

永远不要使用control.CreateGraphics ! 使用Graphics g = Graphics.FromImage(bmp) 使用e.Graphics参数在控件的Paint事件中绘制Bitmap bmp

这是一个裁剪代码,它会绘制一个新的Bitmap并使用你的控件等,但会改变一些事情:

  • 它使用从新Bitmap创建的Graphics对象
  • 它利用using子句来确保它不会泄漏
  • 它需要pictureBox3.ClientSize的大小,所以它不会包含任何边框..

 private void crop_bttn_Click(object sender, EventArgs e) { Image crop = GetCopyImage("grayScale.jpg"); pictureBox2.Image = crop; Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width, pictureBox3.ClientSize.Height); using (Bitmap sourceBitmap = new Bitmap(pictureBox2.Image, pictureBox2.ClientSize.Width, pictureBox2.ClientSize.Height)) { using (Graphics g = Graphics.FromImage(targetBitmap)) { g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox3.ClientSize.Width, pictureBox3.ClientSize.Height), rectCropArea, GraphicsUnit.Pixel); } } if (pictureBox3.Image != null) pictureBox3.Image.Dispose(); pictureBox3.Image = targetBitmap; targetBitmap.Save(somename, someFormat); } 

替代方案是……:

  • 所有代码移动Paint事件
  • 替换Graphics g = pictureBox3.CreateGraphics();Graphics g = e.Graphics;
  • 将这两行插入click事件:

 Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width, pictureBox3.ClientSize.Height); pictureBox3.DrawToBitmap(targetBitmap, pictureBox3.ClientRectangle); 

除非您知道自己在做什么,否则不应使用PictureBox.CreateGraphics()方法,因为它可能会导致一些不那么明显的问题。 例如,在您的场景中,当您最小化窗口或调整窗口大小时, pictureBox3的图像将消失。

更好的方法是绘制一个位图,您也可以保存:

 var croppedImage = new Bitmap(pictureBox3.Width, pictureBox3.Height); var g = Graphics.FromImage(croppedImage); g.DrawImage(crop, new Point(0, 0), rectCropArea, GraphicsUnit.Pixel); g.Dispose(); //Now you can save the bitmap croppedImage.Save(...); pictureBox3.Image = croppedImage; 

顺便说一句,请使用更合理的变量名,特别是pictureBox1..3