Advertisement
Guest User

image_to_ansi.py

a guest
Jun 16th, 2025
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | Source Code | 0 0
  1. #!/usr/bin/env python3
  2. import sys
  3. from PIL import Image
  4.  
  5. def convert_image_to_ansi(image_path):
  6.     try:
  7.         img = Image.open(image_path)
  8.         width, height = img.size
  9.         if width > 80:
  10.             # Calculate new dimensions preserving aspect ratio
  11.             aspect_ratio = height / width
  12.             new_width = 80
  13.             new_height = round(aspect_ratio * new_width)
  14.             width = new_width
  15.             height = new_height
  16.             img = img.resize((width, height))
  17.         new_height = round(height / 2.15) # terminal cells are taller than wide
  18.         img = img.resize((width, new_height))
  19.         if img.mode != 'RGB':
  20.             img = img.convert('RGB')
  21.         ansi_output = ""
  22.         for y in range(new_height):
  23.             for x in range(width):
  24.                 r, g, b = img.getpixel((x, y))
  25.                 ansi_output += f"\033[48;2;{r};{g};{b}m "
  26.             ansi_output += "\033[0m\n" # reset color at EOL
  27.         return ansi_output
  28.     except Exception as e:
  29.         return f"Error processing image: {e}"
  30.  
  31. if __name__ == "__main__":
  32.     if len(sys.argv) < 2:
  33.         print("python image_to_ansi.py <image_path>")
  34.         sys.exit(1)
  35.     image_path = sys.argv[1]
  36.     ansi_art = convert_image_to_ansi(image_path)
  37.     print(ansi_art)
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement