Wednesday, October 1, 2008

How to Save the Output of a Paint Routine in .NET to a Bitmap File or save the image from a picturebox to a bitmap file

Another way to say this is how to save the image from a picturebox to a bitmap file.

I have a Picture box where I load an image at design time.  At runtime, I allow the user the doodle on the image.  I would like to save this image to a bitmap file.  The way I allow the user to draw on the image is through the mousedown and mousemove event I write to an arraylist, and in the PictureBox's paint routine I draw out the contents of the arraylist.  When I try to do a Picturebox1.Image.Save, it doesn't work in that it saves the original image that I loaded at design time, not the one that I just drew on in mousedown and mousemove.  There are two ways the do this.  The harder method is below.  What it does is it creates a tempimage, then it draws to this temp image (what I am assuming here is that you've moved the code from your PictureBox1.Paint routine to a stand alone routine called PaintPictureBox1, this way you can call it from two places), and finally it returns the temp image.

Public Function CurrentPictureBox() as Bitmap

        Dim iNewWidth As Integer, iNewHeight As Integer
        iNewWidth = Int(PictureBox1.Image.Width)
        iNewHeight = Int(PictureBox1.Image.Height)

        tempImage = New Bitmap(iNewWidth, iNewHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb)        
        g = Graphics.FromImage(tempImage)      

        g.DrawImage(PictureBox1.Image, 0, 0, iNewWidth, iNewHeight)
        PaintPictureBox1(g)
    return tempImage
End Sub


The second method is simpler, in that it takes advantage of .NETs DrawToBitmap routine.

Public Function CurrentPictureBox() as Bitmap
            Dim tempImageAs New Drawing.Bitmap(PictureBox1.Image.Width, PictureBox1.Image.Height)
            PictureBox1.DrawToBitmap(tempImage, New Rectangle(0, 0, bmp.Width, bmp.Height))
            return tempImage
End Sub






No comments: