Made a small function to convert the Image to ASCII characters

#2
by Xialah - opened

Hi,

Thank you very much for the model! In return, I've made a small function to convert the Image to ASCII characters.

Best,


from PIL import Image

ASCII_RAMP = "@%#*+=-:. "

def image_to_ascii(img: Image.Image, width=100, invert=False, ramp=ASCII_RAMP):
# 1) Normalize
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")

# 2) Resize with char aspect compensation (~2:1 height)
w, h = img.size
new_h = max(1, int(h / w * width * 0.5))
img = img.resize((width, new_h), Image.BICUBIC).convert("L")

# 3) Pixels as list -> slicing OK
pixels = list(img.getdata())

# 4) Map to ASCII
chars = ramp[::-1] if invert else ramp
n = len(chars) - 1
lines = []
for y in range(img.height):
    row_pixels = pixels[y*img.width:(y+1)*img.width]  # now this slices fine
    row = "".join(chars[int(p / 255 * n)] for p in row_pixels)
    lines.append(row)
return "\n".join(lines)

--- Examples ---

If you already have a PIL.Image object im:

print(image_to_ascii(im, width=120))

Or from a file:

im = Image.open("your_image.png")

ascii_art = image_to_ascii(im, width=120)

print(ascii_art)

Save to a .txt file:

with open("ascii_art.txt", "w", encoding="utf-8") as f:

f.write(ascii_art)

Sign up or log in to comment