ASCII

Here’s a simple Python script that converts an image to ASCII art. It uses the Pillow library to process the image and map pixel values to ASCII characters based on brightness levels.

Script: Convert Image to ASCII Art

from PIL import Image

# Define the ASCII characters based on pixel intensity

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

def resize_image(image, new_width=100):

    """Resize the image maintaining the aspect ratio."""

    width, height = image.size

    aspect_ratio = height / width

    new_height = int(new_width * aspect_ratio * 0.55)  # Adjust for terminal aspect ratio

    return image.resize((new_width, new_height))

def grayify(image):

    """Convert the image to grayscale."""

    return image.convert("L")

def pixels_to_ascii(image):

    """Map each pixel to an ASCII character."""

    pixels = image.getdata()

    ascii_str = "".join(ASCII_CHARS[pixel // 25] for pixel in pixels)  # 256 levels / 10 chars

    return ascii_str

def image_to_ascii(image_path, new_width=100):

    """Convert an image to ASCII art."""

    try:

        image = Image.open(image_path)

    except Exception as e:

        print(f"Unable to open image: {e}")

        return

    image = resize_image(image, new_width)

    gray_image = grayify(image)

    ascii_str = pixels_to_ascii(gray_image)

    ascii_lines = [ascii_str[i:i+new_width] for i in range(0, len(ascii_str), new_width)]

    return "\n".join(ascii_lines)

if __name__ == "__main__":

    import argparse

    parser = argparse.ArgumentParser(description="Convert an image to ASCII art.")

    parser.add_argument("image_path", type=str, help="Path to the input image.")

    parser.add_argument("--width", type=int, default=100, help="Width of the ASCII art.")

    args = parser.parse_args()

    ascii_art = image_to_ascii(args.image_path, new_width=args.width)

    if ascii_art:

        print(ascii_art)

How to Use

1. Install Pillow:

pip install pillow

2. Run the Script:

Save the script as ascii_art.py and run it from the terminal:

python ascii_art.py path_to_image.jpg --width 80

Replace path_to_image.jpg with the path to your image, and adjust --width as needed.

3. Output:

The ASCII art will be printed to the terminal.

Tips

• Use simple images with clear contrast for best results.

• You can modify the ASCII_CHARS variable to customize the style. For example, add more or fewer characters to adjust the gradient.