Search code examples
pythonxmlimagepython-imaging-libraryimgkit

Python: converting an xml file to an image


I am looking to convert a xml file to an image (ideally a png file) using a python script. I have not found much from my online research. I am trying to use PIL. From this post on StackOverflow I was able to find this code:

from PIL import Image
import ImageFont, ImageDraw

image = Image.new("RGBA", (288,432), (255,255,255))
usr_font = ImageFont.truetype("resources/HelveticaNeueLight.ttf", 25)
d_usr = ImageDraw.Draw(image)
d_usr = d_usr.text((105,280), "MYTEXT",(0,0,0), font=usr_font)

But I do not quite understand what's happening. I tried to replace "MYTEXT" with the actual xml file content and it did not work.

I am basically looking for any solution (ideally using PIL, but it can be another module for python). I came close using imgkit:

import imgkit

imgkit.from_file('example_IN.xml','example_OUT.png')

which returns a png file. The resolution of the image is terrible though, and it lies within a very large white rectangle. I may be missing something. I know you can modify options for imgkit, but I have no idea what modifications to bring, even after checking the documentation. Any help would be deeply appreciated.

Thank you so much! Best regards.


Solution

  • I had a go in pyvips:

    #!/usr/bin/env python3
    
    import sys
    import pyvips
    from xml.sax.saxutils import escape
    
    # load first arg as a string
    txt = open(sys.argv[1], "r").read()
    
    # pyvips allows pango markup in strings -- you can write stuff like
    # text("hello <i>sailor!</i>")
    # so we need to escape < > & in the text file
    txt = escape(txt)
    
    img = pyvips.Image.text(txt)
    
    # save to second arg
    img.write_to_file(sys.argv[2])
    

    You can run it like this:

    ./txt2img.py vari.ws x.png
    

    To make this:

    enter image description here

    It's pretty quick -- that took 300ms to run on this modest laptop.

    The text method has a lot of options if you want higher res, to change the alignment, wrap lines at some limit, change the font, etc. etc.

    https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text