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:
Working with images
File I/O in Python
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")
π 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)