from PIL import Image
# Define ASCII characters for different levels of brightness
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def resize_image(image, new_width=100):
"""Resizes the image while maintaining aspect ratio."""
width, height = image.size
aspect_ratio = height / width
new_height = int(new_width * aspect_ratio * 0.55) # Adjusting for terminal aspect ratio
return image.resize((new_width, new_height))
def grayify(image):
"""Converts the image to grayscale."""
return image.convert("L")
def pixels_to_ascii(image):
"""Maps grayscale pixel values to ASCII characters."""
pixels = image.getdata()
ascii_str = "".join(ASCII_CHARS[pixel // 25] for pixel in pixels)
return ascii_str
def convert_image_to_ascii(image_path, new_width=100):
"""Main function to convert image to ASCII art."""
try:
image = Image.open(image_path)
except Exception as e:
print(f"Unable to open image file: {image_path}")
print(e)
return
# Resize and process the image
image = resize_image(image, new_width)
image = grayify(image)
# Convert pixels to ASCII
ascii_str = pixels_to_ascii(image)
img_width = image.width
ascii_str_len = len(ascii_str)
ascii_art = "\n".join(ascii_str[i:i + img_width] for i in range(0, ascii_str_len, img_width))
return ascii_art
def main():
image_path = input("Enter the path to the image file: ")
width = int(input("Enter the desired width of the ASCII art (default is 100): ") or 100)
ascii_art = convert_image_to_ascii(image_path, width)
if ascii_art:
print("\nGenerated ASCII Art:\n")
print(ascii_art)
# Save the ASCII art to a text file
output_file = "ascii_art.txt"
with open(output_file, "w") as f:
f.write(ascii_art)
print(f"\nASCII art has been saved to {output_file}")
if __name__ == "__main__":
main()
No comments:
Post a Comment