Skip to content

Instantly share code, notes, and snippets.

@quotepilgrim
Created April 9, 2024 13:15
Show Gist options
  • Select an option

  • Save quotepilgrim/8c3308151387daa0885a17b2fd145e06 to your computer and use it in GitHub Desktop.

Select an option

Save quotepilgrim/8c3308151387daa0885a17b2fd145e06 to your computer and use it in GitHub Desktop.
import sys
from PIL import Image
def text_to_image(input_file, output_file, width):
bytes_needed = width * width * 3
with open(input_file, "rb") as infile:
file_content = infile.read()
file_size = len(file_content)
if file_size > bytes_needed:
sys.exit("\033[1;31mERROR: text file too big for specified width.")
null_bytes = b"\0" * (bytes_needed - file_size)
padded_content = file_content + null_bytes
img = Image.new("RGB", (width + 2, width + 2), "black")
img.paste(Image.frombytes("RGB", (width, width), padded_content), (1, 1))
r, g, b = img.split()
img = Image.merge("RGB", (b, g, r))
img.save(output_file)
def image_to_text(input_file, output_file):
img = Image.open(input_file)
r, g, b = img.split()
img = Image.merge("RGB", (b, g, r))
image_bytes = img.tobytes()
text_content = image_bytes.replace(b"\0", b"")
with open(output_file, "wb") as outfile:
outfile.write(text_content)
if __name__ == "__main__":
if len(sys.argv) != 4:
print(f"Usage: python {sys.argv[0]} INPUT_TEXT OUTPUT_IMAGE IMAGE_WIDTH")
print(f" or: python {sys.argv[0]} -r INPUT_IMAGE OUTPUT_TEXT")
sys.exit(1)
extract_text = False
args = sys.argv[1:]
if args[0] == "-r":
extract_text = True
args.pop(0)
infile = args.pop(0)
outfile = args.pop(0)
image_width = int(args.pop()) - 2 if args else 0
if extract_text:
image_to_text(infile, outfile)
else:
text_to_image(infile, outfile, image_width)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment