diff --git a/PixelsToSVG/README.md b/PixelsToSVG/README.md new file mode 100644 index 0000000..ab86c70 --- /dev/null +++ b/PixelsToSVG/README.md @@ -0,0 +1,14 @@ +Pixels to SVG +============= + +Convert an image into an SVG file where every pixel is a rectangle object. Good idea? Who knows. + +Usage: + + > pixelstosvg.py [] + + > pixelstosvg.py image.png + Produces image.png.svg + + > pixelstosvg.py image.png special.svg + Produces special.svg \ No newline at end of file diff --git a/PixelsToSVG/pixelstosvg.py b/PixelsToSVG/pixelstosvg.py new file mode 100644 index 0000000..f3cb2f5 --- /dev/null +++ b/PixelsToSVG/pixelstosvg.py @@ -0,0 +1,134 @@ +import argparse +import os +import PIL.Image +import random +import sys + +SVG_TEMPLATE = ''' + + + + + + + image/svg+xml + + + + + + + {rectangles} + + +'''.strip() + +RECTANGLE_TEMPLATE = ''' + +'''.strip() + +def normalize_rgb(rgb, mode): + if mode == '1': + v = rgb * 255 + return (v, v, v, 255) + if mode == 'L': + return (rgb, rgb, rgb, 255) + if mode == 'RGB': + return rgb + (255, ) + if mode == 'RGBA': + return rgb + +def int_to_hex(i): + return hex(i)[2:].rjust(2, '0') + +def rgb_to_hex(rgb): + return '#' + ''.join(int_to_hex(x) for x in rgb) + +def make_svg(image): + rectangles = [] + (width, height) = image.size + for y in range(height): + for x in range(width): + pixel = image.getpixel((x, y)) + pixel = normalize_rgb(pixel, image.mode) + (rgb, opacity) = (pixel[:-1], pixel[-1]) + fill = rgb_to_hex(rgb) + #print(fill) + opacity = opacity / 255 + rectangle = RECTANGLE_TEMPLATE.format( + x=x, + y=y, + width=1, + height=1, + id=str(random.random()), + fill=fill, + opacity=opacity, + ) + rectangles.append(rectangle) + #print(rectangle) + rectangles = '\n'.join(rectangles) + svg = SVG_TEMPLATE.format(width=width, height=height, rectangles=rectangles) + return svg + +def image_to_svg(image_filename, svg_filename=None): + svg_filename = svg_filename or '' + if not svg_filename: + svg_filename = image_filename + '.svg' + + image = PIL.Image.open(image_filename) + svg = make_svg(image) + with open(svg_filename, 'w') as handle: + handle.write(svg) + +def image_to_svg_argparse(args): + return image_to_svg( + image_filename=args.image_filename, + svg_filename=args.svg_filename + ) + +def main(argv): + parser = argparse.ArgumentParser() + + parser.add_argument('image_filename') + parser.add_argument('svg_filename', nargs='?', default=None) + parser.set_defaults(func=image_to_svg_argparse) + + args = parser.parse_args(argv) + args.func(args) + +if __name__ == '__main__': + main(sys.argv[1:])