我有一个包含多个控件和4个图像的面板。 4个图像在框架内。现在我想将4个图片框(在框架中)保存到jpg文件中但是图片框都是白色的,我只看到保存图像中的面板。
Bitmap bmp = new Bitmap(frame.Width, frame.Height);
Rectangle rect = new Rectangle(0, 0, frame.Width, frame.Height);
this.panel1.DrawToBitmap(bmp, rect);
bmp.Save("C:\\Temp\\zo.jpg", ImageFormat.Jpeg);
我该怎么做?
答案 0 :(得分:1)
至少有两种方法可以做到:
PictureBoxes
能够实际显示图像而不切断图像,那么您的代码中的代码将正常工作。注意:PictureBoxes
必须真正位于里面 Panel
(即它必须是Parent
),否则就无法绘制它们!这是一个有效的例子:
private void button1_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
using (Graphics G = Graphics.FromImage(bmp))
panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
// now we can save it..
bmp.Save("d:\\foursome.jpg", ImageFormat.Jpeg);
// and let it go:
bmp.Dispose();
}
DrawImage
在代码中绘制Images
。它更复杂,但为您提供更多控制权:
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
int x1 = 0;
int x2 = Math.Max(pictureBox1.Image.Width, pictureBox3.Image.Width);
int y1 = 0;
int y2 = Math.Max(pictureBox1.Image.Height, pictureBox2.Image.Height);
Rectangle rect1 = new Rectangle(new Point(x1, y1), pictureBox1.Image.Size);
Rectangle rect2 = new Rectangle(new Point(x2, y1), pictureBox2.Image.Size);
Rectangle rect3 = new Rectangle(new Point(x1, y2), pictureBox3.Image.Size);
Rectangle rect4 = new Rectangle(new Point(x2, y2), pictureBox4.Image.Size);
using (Graphics G = Graphics.FromImage(bmp))
{
G.DrawImage(pictureBox1.Image, rect1);
G.DrawImage(pictureBox2.Image, rect2);
G.DrawImage(pictureBox3.Image, rect3);
G.DrawImage(pictureBox4.Image, rect4);
}
bmp.Save("d:\\foursome2jpg", ImageFormat.Jpeg);
// and clean up:
bmp.Dispose();
}
这不仅可以让您添加或删除图像之间的间距,还可以使用this DrawImage format调整它们的大小。当然,你可以添加你想要的任何东西,例如花式框架或文字..