Tuesday, August 4, 2009

Converting a Text File to Image File

You will find useful converting a text file to image file when you have to send a fax through application,
You can find the vb code snippet below for converting the text file to image and save it as your own file type such as tiff file.




Imports System.Drawing
Imports System.Drawing.Graphics
Imports System.Drawing.Imaging

Private Function CreateBitmapImage(ByVal sImageText As String) As Bitmap

Dim objBmpImage As Bitmap = New Bitmap(1, 1)

Dim intWidth As Integer = 0
Dim intHeight As Integer = 0

' Create the Font object for the image text drawing.
Dim objFont As Font = New Font("Arial", 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel)

' Create a graphics object to measure the text's width and height.
Dim objGraphics As Graphics = Graphics.FromImage(objBmpImage)

' This is where the bitmap size is determined.
intWidth = CType(objGraphics.MeasureString(sImageText, objFont).Width, Integer)
intHeight = CType(objGraphics.MeasureString(sImageText, objFont).Height, Integer)

intWidth = 500
intHeight = 900

' Create the bmpImage again with the correct size for the text and font.
objBmpImage = New Bitmap(objBmpImage, New Size(intWidth, intHeight))

' Add the colors to the new bitmap.
objGraphics = Graphics.FromImage(objBmpImage)

' Set Background color
objGraphics.Clear(Color.White)
'objGraphics.SmoothingMode = SmoothingMode.AntiAlias
'objGraphics.TextRenderingHint = TextRenderingHInteger.AntiAlias
'objGraphics.DrawString(sImageText, objFont, New SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0)
objGraphics.DrawString(sImageText, objFont, Brushes.Black, 0, 0)
objGraphics.Flush()

Return (objBmpImage)

End Function

Using it

CreateBitmapImage(strText).Save("D:\Files\FileName.tif",ImageFormat.Tiff)


No comments:

Post a Comment