Skip to content

Instantly share code, notes, and snippets.

@DonBattery
Created November 10, 2023 21:56
Show Gist options
  • Save DonBattery/9d6b1fd449c7504f1dfc6d577e4922cd to your computer and use it in GitHub Desktop.
Save DonBattery/9d6b1fd449c7504f1dfc6d577e4922cd to your computer and use it in GitHub Desktop.
Picture file to bynary
#!/usr/bin/env python3
import argh
from PIL import Image
import argh
def convert(source_filename: str, destination_filename: str = "output.bin"):
"""
Convert an image to a binary file of RGB pixel values.
source_filename: The source image filename.
destination_filename: The destination filename. Defaults to output.bin.
"""
with Image.open(source_filename) as img:
width, height = img.size
# Open the destination file in binary write mode
with open(destination_filename, 'wb') as dest_file:
for y in range(height):
for x in range(width):
pixel = img.getpixel((x, y))
pixel_bytes = bytes([pixel[0], pixel[1], pixel[2]])
dest_file.write(pixel_bytes)
print(
f"Conversion completed. Image written to {destination_filename} as bytes.")
def dump(filename: str = "output.bin"):
"""
Dump the contents of a binary file as integers.
filename: The filename of the binary file to dump. Defaults to output.bin.
"""
with open(filename, 'rb') as file:
byte = file.read(1)
while byte:
# Convert the byte to an integer for printing
byte_value = ord(byte)
print(f"{byte_value} ", end="")
byte = file.read(1)
command_parser = argh.ArghParser()
command_parser.add_commands([convert, dump])
if __name__ == "__main__":
command_parser.dispatch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment