CreateGraphics Problem

OGI

Member
Joined
Mar 20, 2007
Messages
5
Programming Experience
1-3
Hi,
I use the following code to paint an image into my picture box:

imgBox1.CreateGraphics.DrawImage(imgBoxSource.Image, Me.MousePosition)

But when I try to save the image with this function:

imgBox1.Image.Save

a NullReferenceException has occured
Please help me to solve this problem, I want to save my new created graphic as picture like bmp, jpg, png....
Thank you in advance.
 
Your first mistake is that you are not disposing your Graphics object. Every time you call CreateGraphics you MUST dispose the Graphics object it creates when you're done with it:
VB.NET:
Dim g As Graphics = Me.imgBox1.CreateGraphics()

g.DrawImage(...)
g.Dispose()
Your second mistake is that you shouldn't be calling CreateGraphics to draw on a control anyway. You should always draw on controls in their Paint event handler, where a Graphics object is already provided by the 'e' parameter.

Your third mistake is that drawing on a PictureBox control has absolutely no relationship to its Image property at all. If you never assign an Image object to the Image property then it will always be zero. Think of a PictureBox like a photo frame with glass over it. Drawing on the PictureBox is like drawing on the glass. It doesn't mean there's a photo in the frame. If you want an Image in the PictureBox then you have to assign one to the Image property. If you then want to edit that Image you have to darw on the Image itself, not on the PictureBox containing it.
 
Thank you very much for the great advices! Yesterday I successfully completed my Class, and now another one "big" part of my program is finished.
My class paints on a picture control using a picture file for stamp(I'm developing all this stuff because for my 2D strategy game, I hope that one day I shall complete it :) .) here's the class, If you have time you can give me some suggestions to optimize it's work. :

VB.NET:
Public Class PaintMe
    Dim MyBitmap2 As Bitmap
    Dim intCount As Integer = 0
    Dim g As Graphics
    Dim FormForSize As New Windows.Forms.Form
    Sub New()
        FormForSize.Show()
        FormForSize.FormBorderStyle = FormBorderStyle.None
        FormForSize.WindowState = FormWindowState.Maximized
        FormForSize.Visible = False
    End Sub
    Sub DrawMe(ByVal imgSource As PictureBox, ByVal imgHolder As PictureBox)
        intCount += 1
        If intCount = 1 Then
            Dim myBitmap As New Bitmap(FormForSize.Width * 2, FormForSize.Height * 2)
            FormForSize.Dispose()
            MyBitmap2 = myBitmap
        End If
        g = Graphics.FromImage(MyBitmap2)
        g.DrawImage(imgSource.Image, Control.MousePosition)
        imgHolder.Image = MyBitmap2
    End Sub
    Sub SavePaint(ByVal Picture As PictureBox)
        Picture.Image = MyBitmap2
        Picture.Image.Save("oo.png")
    End Sub
End Class
 
Back
Top