Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Converts black and white image to svg as vector pixels. Useful for converting bmp fonts. eg: ` ./bmp_glyphs/ ./svg_glyphs/ bmp`
from PIL import Image
import svgwrite
import os
import argparse
def bmp_to_svg(filename, multiply =1):
img =
w, h = img.size
pixel_acc = img.load()
generated_paths = paths_gen(pixel_acc, w,h, multiply=multiply)
dwg = svgwrite.Drawing(profile='tiny')
for path in generated_paths:
options = path
kwoptions = {} #{"fill":"black"}
dwg.add(dwg.polygon(options, **kwoptions))
#clip_path = dwg.defs.add(dwg.clipPath())
#clip_path.add(dwg.Rect(insert=(0,0), size=((w*multiply)+1, (h*multiply)+1)))
return dwg
def paths_gen(pixel_acc, w, h, multiply = 1):
m = multiply
paths = []
for y in range(0,h):
for x in range(0,w):
pix = pixel_acc[x,y]
brightval = sum(pix) /3
if brightval < 128:
##top left
(x * m, y * m),
##top right
((x+1) * m, y * m),
##bottom right
((x+1) * m, (y+1) * m),
##bottom list
((x) * m, (y+1) * m),
##close back to top left
#(x, y),
return paths
def main():
parser = argparse.ArgumentParser(
description='Script to convert black and white images into vector art')
parser.add_argument("in_ext", default="bmp", help="file extension of images in input folder")
parser.add_argument("-m", "--multiply", default=1, type=int)
#parser.add_argument("-u", "--union", store=True, help="unifies adjecent polgons")
#parser.add_argument("-s", "--simplify", store=True, help="removes points that are part of a straight line")
#parser.add_argument("-c", "--compress", store=True, help="same as '--union --simplify'")
args = parser.parse_args()
cdir = os.path.abspath(args.input_dir)
fn_gen = ( x for x in os.listdir(cdir)
if x.endswith('.'+args.in_ext)
for count, filename in enumerate(fn_gen):
full_filename = os.path.join(cdir, filename)
new_fn = "{}_.svg".format(filename)
new_fullfn = os.path.join(args.ouput_dir, new_fn)
svg = bmp_to_svg(full_filename, multiply=args.multiply)
print "Converted file: '{}'".format(full_filename)
svg.filename = new_fullfn
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment