My Daily Gist | Ferdinand Silva


A Python script that converts an image file to a pure CSS image

 
"""
A Python script that converts an image file to a pure CSS image.
This code was based on a PHP script https://github.com/jaysalvat/image2css.
Sample: https://codepen.io/six519/pen/YzQOKrX
"""
import os
import sys
from PIL import Image
TEMP_FILE = "test.jpg"
if len(sys.argv) > 1:
img = Image.open(sys.argv[1])
img.thumbnail((400, 400), Image.ANTIALIAS)
img.save(TEMP_FILE, "JPEG")
img = Image.open(TEMP_FILE)
print("""
body {
background: black;
}
#img2css {
position: absolute;
top: 30px;
left: 50%;
margin-left: -200px;
width: 0;
height: 0;
box-shadow:
""")
for n1 in range(img.size[0]):
for n2 in range(img.size[1]):
r, g, b = img.getpixel((n1, n2))
sep = ";" if n1 == (img.size[0] - 1) and n2 == (img.size[1] - 1) else ","
print(' {}px {}px 1px 1px #{:02x}{:02x}{:02x}{}'.format(n1, n2, r, g, b, sep))
print("\n}")
os.remove(TEMP_FILE)
view raw img2css.py hosted with ❤ by GitHub