from PIL import Image, ImageDraw, ImageFont import numpy as np import os def imageToAsciiText(path, cell_size=(8, 8)): image = Image.open(path) image = image.convert('L') # Convert to grayscale width, height = image.size pixels = np.array(image) asciiCharacters = "@%#*+=-:. " # From darkest to lightest result = "" for i in range(0, height, cell_size[1]): for j in range(0, width, cell_size[0]): cell = pixels[i:i+cell_size[1], j:j+cell_size[0]] if cell.size == 0: continue averageBrightness = np.mean(cell) characterIndex = int(averageBrightness * (len(asciiCharacters) - 1) / 255) result += asciiCharacters[characterIndex] result += '\n' print(result) return result def asciiTextToImage(asciiText, fontPath, cellSize, fontSize, clarityFactor): # Split the ASCII art into lines lines = asciiText.split('\n') # Calculate the image size needed font = ImageFont.truetype(os.path.join(currentDir, fontPath), fontSize * clarityFactor) max_width = max([len(line) for line in lines]) image_width = max_width * cellSize * clarityFactor image_height = len(lines) * cellSize * clarityFactor # Create a new blank image image = Image.new('RGB', (image_width, image_height), 'white') draw = ImageDraw.Draw(image) # Draw each line of ASCII art y = 0 for line in lines: x = 0 for char in line: draw.text((x, y), char, fill='black', font=font, spacing=0) x += cellSize * clarityFactor y += cellSize * clarityFactor return image # Get the current directory currentDir = os.path.dirname(os.path.abspath(__file__)) # Create the export directory if it doesn't exist exportDir = os.path.join(currentDir, "output") os.makedirs(exportDir, exist_ok=True) # Edit params cellSize = (8, 8) fontPath = 'fonts/courbd.ttf' # Specify the path to your font file fontSize = 10 # font size in points clarityFactor = 8 # Increase this value to improve the clarity of the ASCII art # Process all images in the current directory for filename in os.listdir(currentDir): if filename.endswith(".jpg") or filename.endswith(".png"): # Construct the full path of the image imagePath = os.path.join(currentDir, filename) # Generate the output file name outputFilename = os.path.splitext(filename)[0] + "_asciiart.jpg" outputPath = os.path.join(exportDir, outputFilename) # Call the imageToAsciiText function and save the result to the output file asciiText = imageToAsciiText(imagePath, cellSize) asciiImage = asciiTextToImage(asciiText, fontPath, int(cellSize[0]), fontSize, clarityFactor) asciiImage.save(outputPath) # Print the output file path print(f"Processed image: {outputPath}")