vb.netimagetextimage-generation

How to auto align and adjust text in VB.net that getting converted to Image


I was trying with a code that coverts Text to Image using Vb.net and my problem is I need to accept a message from user (Max 160 Characters) by a text box and i need to convert it to a Image. The generated image should be aligned in the middle and the image max resolution should be 800x600.

So the message should be neatly aligned in new lines if needed and perfectly aligned to the middle.

The code I am trying is as follows:

======================================================

Try

    Dim Text As String = TextBox3.Text

    Dim FontColor As Color = Color.Blue

    Dim BackColor As Color = Color.White

    Dim FontName As String = "Times New Roman"

        Dim FontSize As Integer = 36


        Dim Height As Integer = 60

        Dim Width As Integer = 200

    Dim daten As String
    daten = Now.ToString("ddMMyyyyhhmmss")
    Dim FileName As String = daten
    Dim objBitmap As New Bitmap(Width, Height)
    Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)
    Dim objColor As Color
    objColor = Nothing

    Dim objFont As New Font(FontName, FontSize)

    'Following PointF object defines where the text will be displayed in the

    'specified area of the image

    Dim objPoint As New PointF(5.0F, 5.0F)
    Dim objBrushForeColor As New SolidBrush(FontColor)

    Dim objBrushBackColor As New SolidBrush(BackColor)
    objGraphics.FillRectangle(objBrushBackColor, 0, 0, Width, Height)
    objGraphics.DrawString(Text, objFont, objBrushForeColor, objPoint)
    objBitmap.Save("D:\DNB\" + daten + ".JPG", ImageFormat.Jpeg)
        PictureBox1.Image = Image.FromFile("D:\DNB\" + daten + ".JPG")
    Catch ex As Exception

    End Try

Solution

  • Have you tried the MeasureString function of the Graphics object and it's various overrides? With that you can measure how much space a text in a given size and font needs on the screen. With that knowledge you can calculate the upper left point to use to make the text appear centered.