如何保存在 PictureBox 上创建的图形? [英] How to save graphics created on a PictureBox?
问题描述
在 c# 和 Visual Studio Windows 窗体中,我将图像加载到图片框 (pictureBox2) 中,然后将其裁剪并显示在另一个图片框 (pictureBox3) 中.
In c# and Visual Studio Windows forms I have loaded an image into a picture box (pictureBox2) and then cropped it and show in another picture box (pictureBox3).
现在我想将pictureBox3 中的内容保存为图像文件.
Now I want to save what is inside pictureBox3 as an image file.
我该怎么做?
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)
或绘制到Bitmap bmp
>Painte.Graphics
参数..
Never use control.CreateGraphics
! Either draw into a Bitmap bmp
using a Graphics g = Graphics.FromImage(bmp)
or in the Paint
event of a control, using the e.Graphics
parameter..
这是一个裁剪代码,它绘制到一个新的位图并使用您的控件等,但更改了一些内容:
Here is a cropping code that draws into a new Bitmap and that makes use of your controls etc but changes a few things:
- 它使用从新的
Bitmap
创建的 - 它利用
using
子句来确保它不会泄漏 - 它采用
pictureBox3.ClientSize
的大小,因此它不会包含任何边框..
Graphics
对象- It uses a
Graphics
object that is created from a newBitmap
- It make use of
using
clauses to make sure it won't leak - It takes the size of the
pictureBox3.ClientSize
so it won't include any borders..
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);
}
<小时>
另一种选择是......:
The alternative would be to..:
- 移动所有代码到
Paint
事件 - 将
Graphics g = pictureBox3.CreateGraphics();
替换为Graphics g = e.Graphics;
- 在点击事件中插入这两行:
Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
pictureBox3.ClientSize.Height);
pictureBox3.DrawToBitmap(targetBitmap, pictureBox3.ClientRectangle);
这篇关于如何保存在 PictureBox 上创建的图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!