Saving a Graphics (GDI) object to a file

Guardian

Active member
Joined
Jan 19, 2005
Messages
44
Location
England
Programming Experience
5-10
Hi, i am having problems with my code currently.
What i have is a Picturebox called Canvas, and i am drawing onto it using GDI (i am writing a finite state machine application for my uni project). There is no background image (just a plain white background colour), and my objects which are redrawn every OnPaint event.

What i need to be able to do is to save an image of this canvas (preferably jpeg), to a file.

I tried to do this in a separate subroutine (menu item activate):
VB.NET:
Canvas.Image.Save("", Imaging.ImageFormat.Jpeg)
however, this returned and error (Object reference not set...etc) as on inspection the .image property = nothing.

so i tried to save the image in the paint event, if a flag is set. however i cannot find a way of converting my Graphics object that i am drawing on, to an image.

I have tried searching here, but no luck.

any ideas?

thanks
 
Think of a pen and paper, the Graphics instance is the pen and the bitmap is the paper. Your interest is to save a copy of the paper, not the pen. Here the analogy get a little abstract.. if you draw on top of a control with Paint event you are basically drawing in "thin air", its like smoke, you see it, but just a little shift of winds and its gone.

You have "objects which are redrawn every OnPaint". What you can do is to draw the same thing you drew in control "air" to a bitmap.
The Paint event code can easily be change to something like this:
VB.NET:
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles Me.Paint
  drawobjects(e.Graphics)
End Sub
 
Sub drawobjects(ByVal g As Graphics)
  'draws objects
End Sub
which enables you to save the image using the same draw method:
VB.NET:
Sub saveImage()
  Dim bmp As New Bitmap(400, 400)
  Dim g As Graphics = Graphics.FromImage(bmp)
  drawobjects(g)
  g.Dispose()
  bmp.Save("filename")
End Sub
 

Latest posts

Back
Top