Last active 2 months ago

Converts an image to half-block ascii art with IRC color codes. Uses some code from SCIFv1

Revision 8a4b9a239a49bfcddcccbc285c1e283611bb6d1a

img2ascii.py Raw
1from PIL import Image
2import requests
3from io import BytesIO
4imraw = requests.get("https://cdn.swee.codes/charimgs/altsweecat5.png").content
5im = Image.open(BytesIO(imraw)).convert("RGBA")
6if im.width > 64:
7 new_height = int((64 / im.width) * im.height)
8 im = im.resize((64, new_height))
9px = im.load()
10sz = im.size
11scif = open("e.ascii", "wb")
12empty = 128
13def rgb2irc(r, g, b):
14 palette = [
15 (255, 255, 255), (0, 0, 0),
16 (0, 0, 127), (0, 147, 0),
17 (255, 0, 0), (127, 0, 0),
18 (156, 0, 156), (252, 127, 0),
19 (255, 255, 0), (0, 252, 0),
20 (0, 147, 147), (0, 255, 255),
21 (0, 0, 252), (255, 0, 255),
22 (127, 127, 127), (210, 210, 210),
23 ]
24 return min(range(16), key=lambda i: (r - palette[i][0])**2 + (g - palette[i][1])**2 + (b - palette[i][2])**2)
25for y in range(0, im.height, 2):
26 row = ""
27 for x in range(im.width):
28 r, g, b, a = px[x, y]
29 if y + 1 < im.height:
30 r1, g1, b1, a1 = px[x, y+1]
31 else:
32 r1, g1, b1, a1 = 0, 0, 0, 0
33 top = a >= empty
34 bot = a1 >= empty
35 # Top block will be used if both exist
36 if top and bot:
37 ctop = rgb2irc(r,g,b)
38 cbot = rgb2irc(r1,g1,b1)
39 row += f"\x03{ctop},{cbot}"
40 elif top:
41 c = rgb2irc(r,g,b)
42 row += f"\x03{c},99▀"
43 elif bot:
44 c = rgb2irc(r1,g1,b1)
45 row += f"\x03{c},99▄"
46 else:
47 row += "\x0f "
48 scif.write((row + "\n").encode("utf-8"))
49scif.close()