views:

55

answers:

3

I have two questions:

1) I have a PictureBox and its Dock is set to Fill. When I resize the Form I cannot create a Graphic on the part of the PictureBox that is extended. What is the problem?

2) I want to convert the Graphic that is created on the PictureBox to Bitmap and save it as *.JPG or *.bmp. How can I do this?

A: 

1) Your description is very vague. Do you get an exception? Does it display wrong results? What is happening?

2) You need to get the Image from the PictureBox and use its Save method.

mafutrct
1) I dont get any Eception and it doesnt display wrong result just Grafhic doesnt creat.
Hesam Qodsi
Please try to describe this in more detail... it is really hard to understand what is happening. How do you know it is not created? Is this only if you set Dock to Fill?
mafutrct
You know a PictureBox has an MouseClick event. when i click on the PictureBox i want to draw a rectangle on PictureBox. it is work but when i resize Form to larger beacaus the Dock of PictureBox is Fill it become lrger like Form. after resize i cannot create Grafhic on the part that became larger ..... I hope you understood my problem
Hesam Qodsi
I can explain more: when a Graphics object is created from a control like PictureBox or Panel, the graphics drawn on it are unstable: the Paint event of the control will clear repainted area. for example if you try to show a little dialog on the Control that have Graphics object, after dialog is closed, it's area will be cleared on the Control. another example: move your window into edges of screen, so half of your window falls out of screen view--> now set window to normal, you can't see drawed graphics on the missplaced half...
Sorush Rabiee
+1  A: 

you can use the handle device to get the bitmap out of the picture box

Graphics g = pictureBox1.CreateGraphics();          
Bitmap bitMap = Bitmap.FromHbitmap(g.GetHdc());
bitMap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

or even better, if the pictureBox does`nt modify the image, you can directly get the image from the pictureBox control

pictureBox1.Image.Save("path", System.Drawing.Imaging.ImageFormat.Jpeg);
Alex Pacurar
A: 

When the Picturebox gets resized to fill the form, it seems it's Image property stays the same.

So what you need to do is handle the PictureBox.OnSizeChanged Event, and then use the following code to resize the image:

private void pictureBox1_SizeChanged(object sender, EventArgs e)
{
    if ((pictureBox1.Image != null))
    {
        pictureBox1.Image = new Bitmap(pictureBox1.Image, pictureBox1.Size);
    }
}

To save the image use:

pictureBox1.Image.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);

Hope that helps!

Homeliss
-1: the problem is not related to the Image of PictureBox. He try to draw something stable on a control (PictureBox, Panle or even Form itself).
Sorush Rabiee