1

I'm new to C# and Windows Forms and I would like to save a PictureBox with labels in it in JPEG format.

This is my code so far:

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "JPG(*.JPG)|*.jpg";  
if(sfd.ShowDialog() == DialogResult.OK)
{
    pictureBox1.Image.Save(sfd.FileName, 
System.Drawing.Imaging.ImageFormat.Jpeg);
}

There are labels in the picturebox, but they are not saved as well. Do you have any idea?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • I just dragged them with the mouse in the picturebox, I can't really tell the difference ^^ –  Nov 26 '17 at 12:41
  • And how do I save the picturebox with the labels on top as one image? –  Nov 26 '17 at 12:43
  • 1
    Possible duplicate of [Save Image in PictureBox with overlapping Controls](https://stackoverflow.com/questions/18740077/save-image-in-picturebox-with-overlapping-controls) – mjwills Nov 26 '17 at 12:52
  • Add controls to the `PictureBox`, then `DrawToBitmap` will draw those controls and the `Image` of the `PictureBox` on target bitmap. – Reza Aghaei Nov 26 '17 at 14:03

1 Answers1

0

The most simple option is adding those labels to PictureBox control. Then using DrawToBitmap you can draw those labels and the image to a bitmap:

var bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(bm, new Rectangle(0,0,pictureBox1.Width, pictureBox1.Height));

Then save the bitmap in any format which you need.

Note 1: Don't forget to dispose the bitmap if you don't need it after saving.

Note 2: DrawBitmap draws the labels just if you add them to the Controls collection of the PictureBox:

var label1 = new Label() { 
    Text = "Some Text",
    BackColor = Color.Transparent,
    Location = new Point(10, 10)
};
pictureBox1.Controls.Add(label1);
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Thank, that worked perfectly! When I save the bitmap in jpeg format with my previous code above, the picture is cut off. –  Nov 27 '17 at 16:17
  • Do you have any idea why the image is cut off when saving it?^^ When I move it to the center of the form it gets more visible –  Nov 27 '17 at 16:40
  • I did a correction: `pictureBox1.DrawToBitmap(bm, new Rectangle(0,0,pictureBox1.Width, pictureBox1.Height));`. – Reza Aghaei Nov 27 '17 at 16:45