Skip to content

Instantly share code, notes, and snippets.

@musahibrahimali
Created February 5, 2022 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save musahibrahimali/d5dcfa2c767899fbddbc59a24cafc228 to your computer and use it in GitHub Desktop.
Save musahibrahimali/d5dcfa2c767899fbddbc59a24cafc228 to your computer and use it in GitHub Desktop.
Lets create ASCI images with python
import PIL.Image
ASCII_CHAR = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def resize_image(image, new_width=100):
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return resized_image
def grayify(image):
grayscale_image = image.convert("L")
return grayscale_image
def pixels_to_ascii(image):
pixels = image.getdata()
characters = "".join([ASCII_CHAR[pixel // 25] for pixel in pixels])
return characters
def main(new_width=100):
path = input("Input a valid path to an image: \n")
try:
image = PIL.Image.open(path)
except FileNotFoundError:
print(path, " is not a valid path to an image.")
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
pixel_count = len(new_image_data)
ascii_image = "\n".join(new_image_data[i:(i + new_width)] for i in range(0, pixel_count, new_width))
print(ascii_image)
with open("img/ascii_image.txt", "w") as f:
f.write(ascii_image)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment