Created
May 22, 2024 19:49
-
-
Save gamesbrainiac/c0d437d517f0c94d15d7958555905150 to your computer and use it in GitHub Desktop.
ASCII Art Generator
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
from PIL import Image | |
class ASCIIArtGenerator: | |
def __init__(self, ascii_chars="@%#*+=-:. "): | |
""" | |
Initialize the generator with a string of ASCII characters. | |
The characters should range from darkest to lightest to visually represent different shades. | |
""" | |
# Initialize the ascii_chars attribute with the provided string of characters. | |
def scale_image(self, image, new_width=100): | |
""" | |
Scale the image to a specified width while maintaining the aspect ratio. | |
Returns the scaled image. | |
""" | |
# Calculate the new height of the image maintaining the aspect ratio. | |
# Resize the image to these new dimensions and return it. | |
def convert_to_grayscale(self, image): | |
""" | |
Convert the image to grayscale. | |
This method simplifies processing by discarding color information and focusing on brightness levels. | |
Returns the grayscale image. | |
""" | |
# Use PIL's convert method to change the image mode to 'L' and return the result. | |
def map_pixels_to_ascii(self, image): | |
""" | |
Map each pixel in the grayscale image to an ASCII character based on the pixel's brightness. | |
Returns a string where each pixel's brightness is represented by a specific ASCII character. | |
""" | |
# Get the data from the image using getdata(). | |
# Determine the appropriate character for each pixel based on its value. | |
# Return the concatenated string of ASCII characters. | |
def generate_ascii_art(self, image_path, width=100): | |
""" | |
Generate ASCII art from an image. | |
This function handles the full process: opening the image, scaling it, converting it to grayscale, | |
mapping pixels to ASCII, and formatting the output. | |
Returns the ASCII art as a string. | |
""" | |
# Open the image file from the specified path. | |
# Scale the image to the desired width. | |
# Convert the scaled image to grayscale. | |
# Map the grayscale pixels to ASCII characters. | |
# Format these characters into lines of the specified width and return the result. | |
if __name__ == "__main__": | |
# Example usage of the ASCIIArtGenerator. | |
generator = ASCIIArtGenerator() | |
image_path = "coffee.png" # Replace with the actual image path | |
print(generator.generate_ascii_art(image_path, 100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment