Monday, April 25, 2011

Output text as GIF or PNG for use in eBook

BACKGROUND: My goal is to create an eBook that I can read with the Mobipocket reader on my Blackberry. The problem is that my text includes UTF-8 characters which are not supported on the Blackberry, and therefore display as black boxes.

The eBook will contain a list of English and Punjabi words for reference, such as:

bait          ਦਾਣਾ
baked       ਭੁੰਨਿਆ
balance     ਵਿਚਾਰ

One thought I had was to write the list to an HTML table with the Punjabi converted into a GIF or PNG file. Then include this HTML file in the eBook. All of the words currently exist in an access database, but could easily be exported to another form for input to the generation routines.

QUESTION: Using VB, VBA or C#, how hard would it be to write a routine create the images and then output an HTML file containing the English words and images in a table

From stackoverflow
  • There are easy libraries in Python for handling this kind of problem. However I'm not sure if there is a trivial VB/C# solution.

    With python you'd use the PIL library and code similar to this (which I found here):

    # creates a 50x50 pixel black box with hello world written in white, 8 point Arial text
    import Image, ImageDraw, ImageFont
    
    i = Image.new("RGB", (50,50))
    d = ImageDraw.Draw(i)
    f = ImageFont.truetype("Arial.ttf", 8)
    d.text((0,0), "hello world", font=f)
    i.save(open("helloworld.png", "wb"), "PNG")
    

    If you're already familiar with other languages Python should be pretty easy to pick up, and unlike VB/C# will work on just about any platform. Python can also help you generate the HTML to go along with the generated images. There's some examples of this here.

    Nerdling : nice thorough answer — with citations
    Noah : Wow that looks pretty simple, almost might be worth installing python, just to try it out.
  • Using VB

    Sub createPNG(ByVal pngString As String, ByVal pngName As String)
    
    ' Set up Font
    Dim pngFont As New Font("Raavi", 14)
    
    ' Create a bitmap so we can create the Grapics object 
    Dim bm As Bitmap = New Bitmap(1, 1)
    Dim gs As Graphics = Graphics.FromImage(bm)
    
    ' Measure string.
    Dim pngSize As SizeF = gs.MeasureString(pngString, pngFont)
    
    ' Resize the bitmap so the width and height of the text 
    bm = New Bitmap(Convert.ToInt32(pngSize.Width), Convert.ToInt32(pngSize.Height))
    
    ' Render the bitmap 
    gs = Graphics.FromImage(bm)
    gs.Clear(Color.White)
    gs.TextRenderingHint = TextRenderingHint.AntiAlias
    gs.DrawString(pngString, pngFont, Brushes.Firebrick, 0, 0)
    gs.Flush()
    
    
    'Saving this as a PNG file
    Dim myFileOut As FileStream = New FileStream(pngName + ".png", FileMode.Create)
    bm.Save(myFileOut, ImageFormat.Png)
    myFileOut.Close()
    End Sub
    

0 comments:

Post a Comment