2013-10-03 55 views
1

我有这个代码抛出异常“pictureBox2.Image.Save(st +”patch1.jpg“);”我认为没有什么保存在pictureBox2.Image上,但我已经创建了图形g。 如何保存pictureBox2.Image的图像?保存从图片框中的图像,图像是由图形对象绘制

 Bitmap sourceBitmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height); 
     Graphics g = pictureBox2.CreateGraphics(); 
     g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height),rectCropArea, GraphicsUnit.Pixel); 
     sourceBitmap.Dispose(); 
     g.Dispose(); 
     path = Directory.GetCurrentDirectory(); 
     //MessageBox.Show(path); 
     string st = path + "/Debug"; 
     MessageBox.Show(st); 
     pictureBox2.Image.Save(st + "patch1.jpg"); 

回答

2

有几个问题。

首先,CreateGraphics是一个临时绘图曲面,不适合保存任何东西。我怀疑你要真正创建一个新的形象,并在第二个PictureBox中显示出来:

Bitmap newBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height); 
using (Graphics g = Graphics.FromImage(newBitmap)) { 
    g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel); 
} 
pictureBox2.Image = newBitmap; 

其次,使用Path.Combine函数来创建文件的字符串:

string file = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Debug", "patch1.jpg" }); 
newBitmap.Save(file, ImageFormat.Jpeg); 

这条道路有存在,否则Save方法将抛出一个GDI +异常。

+1

我可能会在OP后3年,但感谢您给我一个需要几个小时才能找到的答案。 – James

1

Graphics g = pictureBox2.CreateGraphics();

你应该阅读了关于这个方法您呼叫的文档,它不是在所有你想要的。这是为了在OnPaint之外进行控制,这是一种不好的做法,会被下一个OnPaint覆盖,并且与PictureBox.Image属性无关,完全没有任何影响。

你究竟在做什么?您想要保存在PictureBox控件中显示的图像的裁剪吗?在将其保存到磁盘之前,是否需要预览裁剪操作?裁剪矩形更改时是否需要更新此预览?提供更多的细节。

1

这样做是相反的。为该位图创建一个目标位图和一个Graphics实例。然后将源图片框图像复制到该位图中。最后,将该位图分配给第二个图片框

Rectangle rectCropArea = new Rectangle(0, 0, 100, 100); 
Bitmap destBitmap = new Bitmap(pictureBox2.Width, pictureBox2.Height); 
Graphics g = Graphics.FromImage(destBitmap); 
g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel); 
g.Dispose(); 
pictureBox2.Image = destBitmap; 
pictureBox2.Image.Save(@"c:\temp\patch1.jpg");