Skip to content

Commit

Permalink
add asciiator feature
Browse files Browse the repository at this point in the history
  • Loading branch information
vatsal-afk committed Oct 16, 2024
1 parent 3bbe524 commit 2ec97dd
Showing 1 changed file with 33 additions and 12 deletions.
45 changes: 33 additions & 12 deletions src/yodapa/plugins/asciiator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,16 @@
import os
import typer

app = typer.Typer()
app = typer.Typer(help="""
Asciiator plugin. Convert an image to ASCII art.
Example:
$ yoda asciiator process "{path to image file}" -s // save output locally
$ yoda asciiator process "{path to image file}" -t // display output on terminal
$ yoda asciiator process "{path to image file}" -s -t // both the actions
""")

ASCII_CHARS = ["#", "?", "%", ".", "S", "+", ".", "*", ":", ",", "@"]

Expand All @@ -16,23 +25,22 @@ def handle_image_conversion(image_filepath):
return

new_width = 100
range_width = 25
(original_width, original_height) = image.size
aspect_ratio = original_height / float(original_width)
new_height = int(aspect_ratio * new_width)

# Resize and convert the image to grayscale
image = image.resize((new_width, new_height)).convert("L")

# Map pixel values to ASCII characters
# Adjust the range width to scale pixel values correctly
range_width = 256 // len(ASCII_CHARS)

pixels_to_chars = "".join(
[
ASCII_CHARS[pixel_value // range_width]
ASCII_CHARS[min(pixel_value // range_width, len(ASCII_CHARS) - 1)]
for pixel_value in list(image.getdata())
]
)

# Create a list of strings for each row of ASCII characters
image_ascii = [
pixels_to_chars[index: index + new_width]
for index in range(0, len(pixels_to_chars), new_width)
Expand All @@ -41,21 +49,34 @@ def handle_image_conversion(image_filepath):
return "\n".join(image_ascii)

@app.command()
def process(input_data):
def process(input_data: str, save: bool = typer.Option(False, "-s", help="Save output to a file"), display: bool = typer.Option(False, "-t", help="Display output in terminal")):
"""
Process an image and convert it to ASCII.
Args:
- input_data: Path to the image file.
- save: Save the ASCII output to a text file.
- display: Display the ASCII output in the terminal.
"""
image_file_path = input_data
data = handle_image_conversion(image_file_path)

if data:
# Get the directory and original file name without extension
if not data:
print("Error converting image.")
return

if save:
directory = os.path.dirname(image_file_path)
base_name = os.path.splitext(os.path.basename(image_file_path))[0]

# Define the output file path
output_file_path = os.path.join(directory, f"{base_name}_ascii.txt")

# Save the ASCII art to a text file
with open(output_file_path, 'w') as f:
f.write(data)

print(f"ASCII art saved to {output_file_path}")

if display:
print(data)

if __name__ == "__main__":
app()

0 comments on commit 2ec97dd

Please sign in to comment.