img2ascii.py
· 1.5 KiB · Python
Raw
from PIL import Image
import requests
from io import BytesIO
imraw = requests.get("https://cdn.swee.codes/charimgs/altsweecat5.png").content
im = Image.open(BytesIO(imraw)).convert("RGBA")
if im.width > 64:
new_height = int((64 / im.width) * im.height)
im = im.resize((64, new_height))
px = im.load()
sz = im.size
scif = open("e.ascii", "wb")
empty = 128
def rgb2irc(r, g, b):
palette = [
(255, 255, 255), (0, 0, 0),
(0, 0, 127), (0, 147, 0),
(255, 0, 0), (127, 0, 0),
(156, 0, 156), (252, 127, 0),
(255, 255, 0), (0, 252, 0),
(0, 147, 147), (0, 255, 255),
(0, 0, 252), (255, 0, 255),
(127, 127, 127), (210, 210, 210),
]
return min(range(16), key=lambda i: (r - palette[i][0])**2 + (g - palette[i][1])**2 + (b - palette[i][2])**2)
for y in range(0, im.height, 2):
row = ""
for x in range(im.width):
r, g, b, a = px[x, y]
if y + 1 < im.height:
r1, g1, b1, a1 = px[x, y+1]
else:
r1, g1, b1, a1 = 0, 0, 0, 0
top = a >= empty
bot = a1 >= empty
# Top block will be used if both exist
if top and bot:
ctop = rgb2irc(r,g,b)
cbot = rgb2irc(r1,g1,b1)
row += f"\x03{ctop},{cbot}▀"
elif top:
c = rgb2irc(r,g,b)
row += f"\x03{c},99▀"
elif bot:
c = rgb2irc(r1,g1,b1)
row += f"\x03{c},99▄"
else:
row += "\x0f "
scif.write((row + "\n").encode("utf-8"))
scif.close()
| 1 | from PIL import Image |
| 2 | import requests |
| 3 | from io import BytesIO |
| 4 | imraw = requests.get("https://cdn.swee.codes/charimgs/altsweecat5.png").content |
| 5 | im = Image.open(BytesIO(imraw)).convert("RGBA") |
| 6 | if im.width > 64: |
| 7 | new_height = int((64 / im.width) * im.height) |
| 8 | im = im.resize((64, new_height)) |
| 9 | px = im.load() |
| 10 | sz = im.size |
| 11 | scif = open("e.ascii", "wb") |
| 12 | empty = 128 |
| 13 | def 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) |
| 25 | for 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")) |
| 49 | scif.close() |