Skip to content

Instantly share code, notes, and snippets.

@poloxue
Last active November 14, 2023 10:11
Show Gist options
  • Save poloxue/b55687913b65f4207fc41150d8330807 to your computer and use it in GitHub Desktop.
Save poloxue/b55687913b65f4207fc41150d8330807 to your computer and use it in GitHub Desktop.
import sys
import click
import pyfiglet
import PIL.Image
def image_to_ascii(path):
try:
img = PIL.Image.open(path)
except:
print(path, "Unable to find image")
exit(1)
width, height = img.size
aspect_ratio = height / width
new_width = 50
new_height = aspect_ratio * new_width * 0.55
img = img.resize((new_width, int(new_height)))
img = img.convert("L")
chars = [" ", "J", "D", "%", "*", "P", "+", "Y", "$", ",", " "]
pixels = img.getdata()
new_pixels = [chars[pixel // 25] for pixel in pixels]
new_pixels = "".join(new_pixels)
new_pixels_count = len(new_pixels)
ascii_image = [
new_pixels[index : index + new_width]
for index in range(0, new_pixels_count, new_width)
]
return "\n".join(ascii_image)
def text_to_ascii(text):
return pyfiglet.figlet_format(text)
@click.command()
@click.option(
"--type",
"type_",
default="text",
help="source type, unavailable options: text, image",
)
@click.option("--source", help="text or image path")
def main(type_, source):
if type_ == "text":
ascii = text_to_ascii(source)
elif type_ == "image":
ascii = image_to_ascii(source)
else:
return
print(ascii)
if __name__ == "__main__":
main()
@poloxue
Copy link
Author

poloxue commented Nov 14, 2023

Install dependencies using the following commands:

pip install pillow
pip install pyfiglet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment