How to convert a string to an image?

  1. use ImageDraw.text – but it doesn’t do any formating, it just prints string at the given location

    img ='RGB', (200, 100))
    d = ImageDraw.Draw(img)
    d.text((20, 20), 'Hello', fill=(255, 0, 0))

    to find out the text size:

    text_width, text_height = d.textsize('Hello')
  2. When creating image, add an aditional argument with the required color (white):

    img ='RGB', (200, 100), (255, 255, 255))
  3. until you save the image with method, there would be no file. Then it’s only a matter of a proper transformation to put it into your GUI’s format for display. This can be done by encoding the image into an in-memory image file:

    import cStringIO
    s = cStringIO.StringIO(), 'png')
    in_memory_file = s.getvalue()

    or if you use python3:

    import io
    s = io.BytesIO(), 'png')
    in_memory_file = s.getvalue()

    this can be then send to GUI. Or you can send direct raw bitmap data:

    raw_img_data = img.tostring()

Leave a Comment