C# 如何保存在PictureBox上创建的图形?
在c#和Visual Studio Windows窗体中,我将图像加载到一个图片框(pictureBox2)中,然后将其裁剪并显示在另一个图片框(pictureBox3)中 现在我想将pictureBox3中的内容保存为图像文件 我该怎么做C# 如何保存在PictureBox上创建的图形?,c#,winforms,graphics,crop,picturebox,C#,Winforms,Graphics,Crop,Picturebox,在c#和Visual Studio Windows窗体中,我将图像加载到一个图片框(pictureBox2)中,然后将其裁剪并显示在另一个图片框(pictureBox3)中 现在我想将pictureBox3中的内容保存为图像文件 我该怎么做 private void crop_bttn_Click(object sender, EventArgs e) { Image crop = GetCopyImage("grayScale.jpg"); pictureBox2.Image
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();
}
除非您知道自己在做什么,否则不应使用方法
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
永远不要使用control.CreateGraphics
使用Graphics g=Graphics.FromImage(bmp)
或使用e.Graphics
参数在控件的Paint
事件中绘制位图bmp
下面是一个裁剪代码,它将绘制到新位图中,并使用控件等,但会更改一些内容:
- 它使用从新的
位图创建的
对象图形
- 它使用
和
子句来确保它不会泄漏
- 它采用
pictureBox3.ClientSize的大小,因此不包含任何边框
另一种选择是
- 将所有代码移动到
事件Paint
- 替换
Graphics g=pictureBox3.CreateGraphics()代码>be
图形g=e.图形代码>
- 在单击事件中插入以下两行:
您是否尝试过:?
Graphics g=pictureBox3.CreateGraphics()无法保存使用此(无效)图形对象创建的代码>内容。将代码更改为仅在绘制中绘制,即使使用e.Graphics对象t!!!-或者(这里可能更好)绘制成位图。前者可以使用pbox.DrawToBitMap保存,然后(对于两者)使用bitmap.Save保存。对于后者,使用aGraphics g=Graphics.FromImage(bmp)
@TaW-我不太明白你说的。请你解释一下或者给我看看代码好吗。我真的很想解决这个问题,我的整个项目都被困在这里了。@Stefan-是的,我有。但是这些似乎都不起作用。非常感谢。我采用了第一种方法,它解决了我的问题。
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);
}
Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
pictureBox3.ClientSize.Height);
pictureBox3.DrawToBitmap(targetBitmap, pictureBox3.ClientRectangle);