Have you ever encountered those captivating images crafted entirely from text characters? That's the magic of ASCII art, a creative method for representing visual information using text. This article delves into Python code that empowers you to transform your favorite images into this unique format.
Understanding the Code
- We'll be working with Python and the Pillow library (often shortened to PIL) for image manipulation. Here's a breakdown of the essential functions:
1.Resizing Images (resize_img
):
def resize_img(image, new_width=100):
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio)
resized_img = image.resize((new_width, new_height))
return resized_img
- This function receives an image and an optional new desired width.
- It calculates the proportional height based on the original aspect ratio to maintain proportions during resizing.
2.Converting to Grayscale(pixel_to_grayscale
):
def pixel_to_grayscale(image):
grayscale_img = image.convert("L") # "L" mode for grayscale
return grayscale_img
- This function converts the image from its original colors to grayscale.
- Grayscale representations simplify the process of mapping pixel brightness levels to ASCII characters later
3.Converting Pixels to ASCII(pixel_to_ascii
):
def pixel_to_ascii(image):
pixels = image.getdata()
characters = "".join(ASCII_CHAR[pixel // 25] for pixel in pixels)
return characters
ASCII_CHAR = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
- This function is the core of the conversion.
- It iterates through each pixel in the grayscale image and assigns a corresponding ASCII character based on its brightness.
- The ASCII_CHAR list acts as a reference, with darker characters representing darker pixels for a textured effect.
4.Main Function (main
):
def main(new_width=100):
path = input("Enter the path of the image: \n")
try:
image = Image.open(path)
except Exception as e:
print(f"{path} is not a valid path!")
print(e)
return
# Convert to grayscale and ASCII art
grayscale_image = pixel_to_grayscale(resize_img(image))
new_image_data = pixel_to_ascii(grayscale_image)
pixel_nb = len(new_image_data)
ascii_img = "\n".join(new_image_data[i:i + new_width] for i in range(0, pixel_nb, new_width))
print(ascii_img) # Print the ASCII art to the console
try:
with open("asciiArt.txt", "w") as c:
try:
c.write(ascii_img)
except Exception as e:
print(f"Error while writing to the file: {e}")
except Exception as e:
print(f"Error while opening the file: {e}")
main()
- This function brings everything together.
- It prompts the user for an image path, handles potential exceptions, and sequentially calls other functions: Resizes the image.
- Converts it to grayscale.
- Converts pixels to ASCII characters.
- Prints the ASCII art to the console.
- Attempts to save the ASCII art to a text file named “asciiArt.txt”
Top comments (0)