Techno

things which came out my laptop

Batch Convert PNG Into SVG Using Python

| Comments

Recently I am working on product where I have been assigned to some interesting charting related tasks. As part of an assignment, I needed to convert bunch of PNGs to SVGs with embedded base64 png image as charting API I was working on written to accept SVG only so I wrote following python script which does this bulk conversion.

(png2svg.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import os
startSvgTag = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="240px" height="240px" viewBox="0 0 240 240">"""

endSvgTag = """</svg>"""
for files in os.listdir("."):
    if files.endswith(".png"):
      pngFile = open(files, 'rb')
      base64data = pngFile.read().encode("base64").replace('\n','')
      base64String = '<image xlink:href="data:image/png;base64,{0}" width="240" height="240" x="0" y="0" />'.format(base64data)

      f = open(os.path.splitext(files)[0]+".svg",'w')
      f.write( startSvgTag + base64String + endSvgTag)
      print 'Converted '+ files + ' to ' + os.path.splitext(files)[0]+".svg"

Basically we will be converting PNG image to base64 format string and we will be using it an SVG using the template String by string concatenation. A Just run this script in directory where you have your pngs.

1
sachin@sachin-VPCF226FM:~/download/icons$ python png2svg.py

Life is short - you need Python!

Comments