我有这段代码在“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");
请您参考如下方法:
几个问题。
首先,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+ 异常。
