Skip to content

Instantly share code, notes, and snippets.

@TypeA2
Created November 3, 2025 10:16
Show Gist options
  • Select an option

  • Save TypeA2/754d39e644d5567acf93085aeb0406f0 to your computer and use it in GitHub Desktop.

Select an option

Save TypeA2/754d39e644d5567acf93085aeb0406f0 to your computer and use it in GitHub Desktop.
Convert Danbooru posts (by ID) to Sixel format
#!/usr/bin/env python3
import sys
import math
import io
import requests as re
from itertools import groupby
from PIL import Image
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <post ID>")
exit(1)
post_url = re.get(f"https://danbooru.donmai.us/posts/{sys.argv[1]}.json", params={ "only": "file_url"})
if post_url.status_code != 200:
print(f"API error {post_url.status_code}")
exit(1)
post_data = re.get(post_url.json()["file_url"], stream=True)
if post_data.status_code != 200:
print(f"Download error {post_data.status_code}")
exit(1)
img = Image.open(post_data.raw) # type: ignore
img = img.convert(mode="P", palette=Image.Palette.ADAPTIVE, dither=Image.Dither.FLOYDSTEINBERG)
w, h = img.size
sixel_string = io.StringIO()
# Start Sixel mode
sixel_string.write("\x1bPq")
# Write palette
assert img.palette is not None
for color, index in img.palette.colors.items():
r, g, b = color
r = round(r * (100 / 255))
g = round(g * (100 / 255))
b = round(b * (100 / 255))
sixel_string.write(f"#{index};2;{r};{g};{b}")
img_data = img.tobytes()
for row in range(math.ceil(h / 6)):
y = row * 6
sixels = [0] * w * 256
for x in range(w):
for i in range(6):
if y + i >= h:
break
sixels[(img_data[((y + i) * w) + x] * w) + x] |= (1 << i)
for i in range(256):
chunk = sixels[i * w : (i + 1) * w]
if not any(chunk) and i != 255:
continue
row = f"#{i}"
for k, g in groupby(chunk):
count = len(list(g))
if count > 1:
row += f"!{count * 2}{chr(k + 63)}"
else:
row += chr(k + 63) * count * 2
if i == 255:
row += "-"
else:
row += "$"
sixel_string.write(row)
# End Sixel mode
sixel_string.write("\x1b\\")
full_string = sixel_string.getvalue()
# print(f"{len(full_string)} characters")
print(full_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment