Link to home
Start Free TrialLog in
Avatar of Salah a a a Al Jasem
Salah a a a Al JasemFlag for Kuwait

asked on

vb.net PictureBox saving the content

I am trying to load an image, place a text, draw lines, then save.
The following is my code, it loads ok, draws ok, but saving saves only the loaded image without the placed text or lines.

Is there a way to solve it?

        Dim FontNameIs, TextLineIs As String
        Dim FontSizeIs, CurrX, CurrY As Integer
        Dim fontToMeasure As New Font("Microsoft Sans Serif", 14, FontStyle.Bold)

        PictureBox1.Load("MyPictureFile.JPG")

        TextLineIs = "Text to be placed on top of MyPictureFile.jpg"
        FontNameIs = "Arial"
        FontSizeIs = 14
        CurrX = 20
        CurrY = 50

        PictureBox1.CreateGraphics.DrawString(TextLineIs, New Font(FontNameIs, FontSizeIs), Brushes.Black, CurrX, CurrY) 'placing a text

        Dim P As Pen = New Pen(Color.Black)
        PictureBox1.CreateGraphics.DrawLine(P, 20, 50, 492, 50) 'drawing a line

        If PictureBox1.Image IsNot Nothing Then
            PictureBox1.Image.Save("C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
        End If
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Salah a a a Al Jasem

ASKER

There is an error with filemode in line

Using fs As New System.IO.FileStream(fileName, FileMode.Open)

so I added the following
Imports System
Imports System.IO
Imports System.Text

The error disappeared and I was able to run
It is very good code

Thank you Mr Mike Tomlinson
the code is perfect
By the way, you can actually do the drawing "in the PictureBox" itself, as you were originally attempting.  To do so, however, you would NOT use CreateGraphics().  Instead, you'd draw your text/line using the supplied "e.Graphics" of the Paint() event of the PictureBox.  Then you'd dynamically create a Bitmap the same size as your PictureBox and pass that to the PictureBox.DrawToBitmap()  method.  Afterwards you'd use the Bitmap.Save() method.