KKosty4ka

textwall image converter

Sep 3rd, 2023
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. from PIL import Image
  4. import math
  5. import sys
  6.  
  7. """
  8. le one and only:
  9. textwall image converter™
  10. by KKosty4ka
  11. version 1.0.0
  12.  
  13. usage:
  14. ./textwall_image_converter.py image.png image.txt
  15. the image msut have even height cuz im lazy
  16.  
  17. now go to textwall and spam goatse all over spawn
  18. """
  19.  
  20. PALLETE = {
  21.     0x80: (0, 0, 0),
  22.     0x9e: (81, 82, 82),
  23.     0x81: (137, 141, 144),
  24.     0x82: (212, 215, 217),
  25.     0x97: (109, 0, 26),
  26.     0x8f: (190, 0, 57),
  27.     0x84: (255, 69, 0),
  28.     0x85: (255, 168, 0),
  29.     0x87: (255, 214, 53),
  30.     0x98: (255, 248, 184),
  31.     0x90: (0, 163, 104),
  32.     0x89: (0, 204, 120),
  33.     0x88: (126, 237, 86),
  34.     0x91: (0, 117, 111),
  35.     0x92: (0, 158, 170),
  36.     0x99: (0, 204, 192),
  37.     0x8c: (36, 80, 164),
  38.     0x8b: (54, 144, 234),
  39.     0x8a: (81, 233, 244),
  40.     0x93: (73, 58, 193),
  41.     0x94: (106, 92, 255),
  42.     0x9a: (148, 179, 255),
  43.     0x8e: (129, 30, 159),
  44.     0x8d: (180, 74, 192),
  45.     0x9b: (228, 171, 255),
  46.     0x9c: (222, 16, 127),
  47.     0x95: (255, 56, 129),
  48.     0x83: (255, 153, 170),
  49.     0x96: (109, 72, 47),
  50.     0x86: (156, 105, 38),
  51.     0x9d: (255, 180, 112)
  52. }
  53.  
  54. img = Image.open(sys.argv[1])
  55. width, height = img.size
  56. pix = img.load()
  57. output = ("█" * width + "\n") * (height // 2) + "\x1b"
  58. output = bytearray(output, encoding="utf8")
  59.  
  60. def color_distance(a: tuple, b: tuple) -> float:
  61.     return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)
  62.  
  63. def nearest_color(color: tuple) -> int:
  64.     nearest = 0
  65.     nearest_dist = 9999999999
  66.    
  67.     for k, v in PALLETE.items():
  68.         dist = color_distance(color, v)
  69.  
  70.         if dist < nearest_dist:
  71.             nearest = k
  72.             nearest_dist = dist
  73.    
  74.     return nearest
  75.  
  76. for y in range(0, height, 2):
  77.     for x in range(width):
  78.         col1 = pix[x, y]
  79.         col2 = pix[x, y + 1]
  80.        
  81.         avg = (
  82.             (col1[0] + col2[0]) // 2,
  83.             (col1[1] + col2[1]) // 2,
  84.             (col1[2] + col2[2]) // 2
  85.         )
  86.  
  87.         output.append(0xc3)
  88.         output.append(nearest_color(avg))
  89.    
  90.     output.append(0xc3)
  91.     output.append(0x80)
  92.  
  93. with open(sys.argv[2], "wb") as f:
  94.     f.write(output)
Add Comment
Please, Sign In to add comment