Create a text in an image - VB-Script


' Visual Basic Scripting Example 02
'
' "Center a text in a large image"
'


CenterText

Sub CenterText()

 Dim imageobj
 Dim fontobj
 Dim text
 Dim height
 Dim width
 Dim top
 Dim left
 Dim path

 ' Fix path
 path = Server.MapPath("..\..\images") & "\"

 Set imageobj = Server.CreateObject("W3Image.Image")

 ' Create a small surface (needed in order to perform any font operation)
 imageobj.CreateEmptySurface 1,1

 ' Create and select the font (shadow)
 Set fontobj = imageobj.CreateFont("Tahoma",60,0,"normal",0,&H000000&,false,false,true)
 imageobj.SetFont fontobj

 ' Text to center
 text = "w3 Image is the answer..."

 ' Get size of the text
 width = imageobj.GetTextWidth(text)
 height = imageobj.GetTextHeight(text)

 ' Load the image
 If (imageobj.LoadImage(path & "sunset.jpg") = False ) then
  ' Do your error handling here...
  DisplayError "Error when loading image 'sunset.jpg'. Path " & path & "sunset.jpg is probably invalid."
  ' Jump out - otherwise the code will continue
  Exit Sub
 End If

 ' Set back to transparency (JPG is not transparent!)
 ' New 2.0
 imageobj.bkMode = 1;

 ' Scale the image (make it double size)
 imageobj.Scale 200

 ' Important!!!! Select the font again (is lost when creating a new surface)
 imageobj.SetFont fontobj

 top = ((imageobj.height - height)/2)
 If (top < 0) then
  top = 0
 End If

 left = ((imageobj.width - width)/2)
 If (left <= 0) then
  left = 0
 End If

 ' Draw the shadow text
 imageobj.DrawText text, left, top

 ' Create and select a new font
 Set fontobj = imageobj.CreateFont("Tahoma",60,0,"normal",0,&H00E2A701&,false,false,true)
 imageobj.SetFont fontobj

 ' Draw the text
 imageobj.DrawText text, left + 3, top + 3

 If (imageobj.StreamImage(Response, "BMP", 24) = False ) Then
  ' Do your error handling here...
  DisplayError "Error when streaming the image."
 End If

End Sub

' Example of a error handler - Displaying the error as a image
Sub DisplayError(msgcode)

 ' Create an error image
 Dim errorimage
 Dim fontobj
 Dim width
 Dim height

 Set errorimage = Server.CreateObject("W3Image.Image")
 errorimage.CreateEmptySurface 1,1

 ' Create and select the font
 Set fontobj = errorimage.CreateFont("Tahoma",24,0,"normal",0,&H00000000&,False,False,True)
 errorimage.SetFont fontobj

 ' Get size of the text
 width = errorimage.GetTextWidth(msgcode)
 height = errorimage.GetTextHeight(msgcode)

 ' Create a surface as large as the error message
 errorimage.CreateEmptySurface width,height

 ' Select the font again (font is deselected when creating a new surface)
 errorimage.SetFont fontobj

 ' Write out error message
 errorimage.DrawText msgcode,0,0

 ' Stream the image
 errorimage.StreamImage Response, "JPG", 24

End Sub