Skip to content

Instantly share code, notes, and snippets.

@mbasaglia
Last active July 23, 2017 21:34
Show Gist options
  • Save mbasaglia/aa6f94b379cfa96ab34adf60a605be13 to your computer and use it in GitHub Desktop.
Save mbasaglia/aa6f94b379cfa96ab34adf60a605be13 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
from argparse import ArgumentParser
from PIL import Image
import svgwrite
def pix2char(image, x, y, palette):
try:
l, a = image.getpixel((x, y))
except IndexError:
return ""
val = ((1 - l / 255.0) * a / 255.0)
index = int(val * (len(palette) - 1))
return palette[index]
parser = ArgumentParser(add_help=False)
parser.add_argument(
"input"
)
parser.add_argument(
"output"
)
parser.add_argument(
"--palette", "-p",
default=" .-:asdgMX#",
)
parser.add_argument(
"--subchar", "-s",
type=int,
default=1,
)
parser.add_argument(
"--width", "-w",
type=int,
default=None,
)
parser.add_argument(
"--height", "-h",
type=int,
default=None,
)
parser.add_argument(
"--font-size", "-f",
type=int,
default=12,
)
options = parser.parse_args()
image = Image.open(options.input).convert('LA')
subchar = options.subchar
text = [""] * (subchar ** 2)
if options.width or options.height:
width = options.width or image.size[0] * options.height / image.size[1]
height = options.height or image.size[1] * width / image.size[0]
image.thumbnail((width, height))
for y in xrange(0, image.size[1], subchar):
for x in xrange(0, image.size[0], subchar):
for subchar_y in xrange(0, subchar):
for subchar_x in xrange(0, subchar):
index = subchar_x + subchar_y * subchar
text[index] += pix2char(image, x+subchar_x, y+subchar_y, options.palette)
for i in xrange(len(text)):
text[i] += "\n"
font_size = options.font_size
svg = svgwrite.Drawing(options.output)
svg.add(svg.style("""
text {{
letter-spacing: {letter_spacing}px;
font-size: {font_size}px;
font-family: monospace;
fill: rgba(0, 0, 0, {alpha});
font-weight: bold;
white-space:pre;
}}""".format(
font_size=font_size,
letter_spacing=font_size,
alpha=1.0 / (subchar ** 2),
)))
g = svg.g(transform="scale(1.25, 1)")
for subchar_y in xrange(0, subchar):
for subchar_x in xrange(0, subchar):
index = subchar_x + subchar_y * subchar
g.add(svg.text(text[index], insert=(
subchar_x * font_size / float(subchar),
subchar_y * font_size / float(subchar),
)))
svg.add(g)
svg.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment