Search code examples
vb.netpicturebox

save image with text to .png


i have a picture box with image, i add text to image. this works fine. here is code snippet

 Dim MyImg As New Bitmap(PicCropImage.Image)
            Dim MyRect As New Rectangle(0, 0, PicCropImage.Width, PicCropImage.Height)
            PicCropImage.BackColor = Color.White
            Dim g As Graphics = PicCropImage.CreateGraphics

            Using g
                g.SmoothingMode = SmoothingMode.HighQuality
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
                g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
                g.DrawString(TxtPhotoCaption.Text, FNT, New SolidBrush(CboPhotoCaptionColor.Color), MyRect, format)
                g.DrawImage(MyImg, MyImg.Width, MyImg.Height)
            End Using

            Dim bmpImage As New Bitmap(PicCropImage.Image)

            bmpImage.Save("C:\Users\<username>\Desktop\test8.png", Imaging.ImageFormat.Png)
            bmpImage.Dispose()
            MyImg.Dispose()

text on image

problem is when i save the image, the text is not save with it?? no text on image

can anyone point the error or correct way to add text to image and save the new image with text on it??


Solution

  • The problem is that you are creating the Graphics object for the PictureBox itself, rather than the Image in the PictureBox. It's like you have a photo behind glass in a frame and you are writing on the glass, then wondering why the picture doesn't have any writing on it. You should be using code like this:

    Using img As New Bitmap(PicCropImage.Image)
        Using g = Graphics.FromImage(img)
            'Use g here.
        End Using
    
        img.Save("C:\Users\<username>\Desktop\test8.png", Imaging.ImageFormat.Png)
    End Using
    

    NEVER call CreateGraphics. If you find yourself doing so, there is a statistically 100% chance that you're doing something wrong.

    Note that that is if you want to draw on a copy of the Image in the PictureBox.