DEV Community

Cover image for Creating ASCII Art from an Image with Python 🐍
Mintah Andrews
Mintah Andrews

Posted on

Creating ASCII Art from an Image with Python 🐍

Coding in Python can be surprisingly easy β€” and fun! One cool project is turning any image into ASCII art using just a few lines of code. TIKTOK

This project is beginner-friendly and helps you practice:

  1. Working with images

  2. File I/O in Python

  3. String manipulation

Here’s a quick demo πŸ‘‡

from PIL import Image

ASCII characters used to build the output text

ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]

def resize_image(image, new_width=100):
    width, height = image.size
    ratio = height / width / 1.65
    new_height = int(new_width * ratio)
    return image.resize((new_width, new_height))

def grayify(image):
    return image.convert("L")

def pixels_to_ascii(image):
    pixels = image.getdata()
    characters = "".join([ASCII_CHARS[pixel // 25] for pixel in pixels])
    return characters

def main(image_path, new_width=100):
    try:
        image = Image.open(image_path)
    except:
        print(image_path, "is not a valid pathname to an image.")
        return

    image = resize_image(image)
    image = grayify(image)

    ascii_str = pixels_to_ascii(image)
    img_width = image.width
    ascii_str_len = len(ascii_str)

    ascii_img = "\n".join([ascii_str[index:(index+img_width)] for index in range(0, ascii_str_len, img_width)])

    print(ascii_img)

    with open("ascii_image.txt", "w") as f:
        f.write(ascii_img)

main("your_image.jpg")
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Replace "your_image.jpg" with the path to your image.
πŸ‘‰ Run the script and you’ll get an ASCII art version saved in ascii_image.txt.

#python #beginners #programming #tutorial #asciiart

Top comments (0)