How to save graphics to file from a picturebox in vb.net

Posted: Wednesday 27 February 2013

If you're like me and you've been trying to desperately convert a picture box that uses CreateGraphics() to bitmap or any other image in VB.net, you'll find that you can't do it. The object that that creates can only seemingly be accessed by .GetHdc(), however using Bitmap.FromHbitmap(objcanvas.GetHdc()) results in an error..
So basically, trying to create an image out of "PictureBox1.CreateGraphics()" is impossible. It won't work..
Instead, define a new Bitmap [let's call it bitmap] and use Graphics.FromImage(bitmap) instead of PictureBox1.CreateGraphics(). If you're worried about the PictureBox not updating since the graphic is not bound to the picturebox then don't worry, you can later set the image of the picturebox from that bitmap that you created and it will be updated with changes made to the graphic.
So codewise, if you're trying this:
    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        objpaint = Graphics.CreateGraphics()
    End Sub

    Private Sub SaveAsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveAsToolStripMenuItem.Click
        If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PictureBox15.Image = Bitmap.FromHbitmap(objpaint.GetHdc())
            PictureBox15.Image.Save(SaveFileDialog1.FileName.ToString(), Imaging.ImageFormat.Bmp)
        End If
Then it doesn't work, because of how the graphics is handled..
However, the following works:
    Dim bitmap = New Bitmap(Width, Height)

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        objpaint = Graphics.FromImage(bitmap)
        objpaint.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy
    End Sub

    Private Sub SaveAsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveAsToolStripMenuItem.Click
        If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PictureBox15.Image = bitmap
            PictureBox15.Image.Save(SaveFileDialog1.FileName.ToString(), Imaging.ImageFormat.Bmp)
        End If
    End Sub
And to update the PictureBox to reflect the graphics, just do this:  PictureBox15.Image = bitmap