Python: converting an xml file to an image

8k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

The solution suggested above by jcuppit using pyvips definitely works and is quick. I found another solution to make my previous code above work using imgkit (it is slower, I am giving it here just for reference): the resolution of the output image was bad. If this happens, width and height can be changed in the options (this is an easy fix I had missed):

import imgkit

options = {
    'width' : 600,
    'height' : 600
}

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

And that will convert a xml file into a png file as well.