I have a PictureBox
on my Windows Forms application.
I load a picture in it and I have enabled the Paint
event in my code. It draws a rectangle.
Like this:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics gr = e.Graphics;
Pen p = new Pen(Color.Red);
p.Width = 5.0f;
gr.DrawRectangle(p, 1, 2, 30, 40);
}
And I click the "save" button:
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
}
But the saved file never contains the rectangle that I drew.
Does anyone have any idea?
Here is my solution with additional support to various file types:
public void ExportToBmp(string path)
{
using(var bitmap = new Bitmap(pictureBox.Width, pictureBox.Height))
{
pictureBox.DrawToBitmap(bitmap, pictureBox.ClientRectangle);
ImageFormat imageFormat = null;
var extension = Path.GetExtension(path);
switch (extension)
{
case ".bmp":
imageFormat = ImageFormat.Bmp;
break;
case ".png":
imageFormat = ImageFormat.Png;
break;
case ".jpeg":
case ".jpg":
imageFormat = ImageFormat.Jpeg;
break;
case ".gif":
imageFormat = ImageFormat.Gif;
break;
default:
throw new NotSupportedException("File extension is not supported");
}
bitmap.Save(path, imageFormat);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With