Created
February 5, 2022 01:41
-
-
Save musahibrahimali/d5dcfa2c767899fbddbc59a24cafc228 to your computer and use it in GitHub Desktop.
Lets create ASCI images with python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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