1

I was wondering is there a way to create an SVG image with PIL library?

I need to create a black square of about 500x500px and add some simple text to it, I know this is an easy task for PIL. But I couldn't find any way to save it as SVG to my computer

Eugene
  • 57
  • 1
  • 7

2 Answers2

2

PIL/Pillow is a raster image processor, a.k.a. bitmap image processor and incapable of generating vector output such as SVG.

However, if you really just need a 500x500 black rectangle with some simple text, you can write that yourself without any library dependencies:

#!/usr/bin/env python3

# Create SVG string - more examples here https://www.w3schools.com/graphics/svg_intro.asp
svg = """<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
  <rect width="500" height="500" style="fill:rgb(0,0,0)" />
  <text x="20" y="200" fill="yellow">Some simple text.</text>
</svg>
"""

# Write to a text file
with open('image.svg', 'w') as f:
    f.write(svg)

The file contents obviously look like the string svg in the code, and you can convert it to a PNG for viewing with ImageMagick like this:

magick image.svg result.png

You could equally use your web browser to visualise it by clicking on File->Open File and selecting image.svg

enter image description here

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

You could also try svgwrite, and save yourself the effort of hand-crafting XML. It's no longer in active development, but the sample script seems to work.

Huw Walters
  • 1,888
  • 20
  • 20