Create graphic and save it as Bitmap
17,547
Solution 1
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);
Solution 2
Try this, works fine for me...
private void SaveControlImage(Control ctr)
{
try
{
var imagePath = @"C:\Image.png";
Image bmp = new Bitmap(ctr.Width, ctr.Height);
var gg = Graphics.FromImage(bmp);
var rect = ctr.RectangleToScreen(ctr.ClientRectangle);
gg.CopyFromScreen(rect.Location, Point.Empty, ctr.Size);
bmp.Save(imagePath);
Process.Start(imagePath);
}
catch (Exception)
{
//
}
}
Related videos on Youtube
Comments
-
Hesam Qodsi about 2 years
I have two questions:
1) I have a
PictureBox
and its Dock is set to Fill. When I resize theForm
I cannot create a Graphic on the part of thePictureBox
that is extended. What is the problem?2) I want to convert the Graphic that is created on the
PictureBox
toBitmap
and save it as *.JPG or *.bmp. How can I do this? -
Hesam Qodsi almost 14 years1) I dont get any Eception and it doesnt display wrong result just Grafhic doesnt creat.
-
mafu almost 14 yearsPlease 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?
-
Hesam Qodsi almost 14 yearsYou 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
-
sorush-r almost 14 yearsI 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-r almost 14 years-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).
-
Zorgarath over 7 yearsI tried this before, unfortunately the image you are saving is then restricted to the size of the control itself. So if you are using zoom to fit a huge image into a control, when you export the image it will be the rendered size and not its actual size.