Created
January 18, 2023 20:11
-
-
Save francisrstokes/d3f044618757ba9a770125d671f691e1 to your computer and use it in GitHub Desktop.
Binary visualizer, inspired by scanlime
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
#!/usr/bin/env python | |
import math | |
import subprocess | |
from random import choice | |
from argparse import ArgumentParser | |
def random_filename(): | |
letters = [chr(ord("a") + x) for x in range(26)] | |
return "".join([choice(letters) for _ in range(12)]) | |
parser = ArgumentParser("visbin") | |
parser.add_argument("input_file") | |
parser.add_argument("width", type=int) | |
parser.add_argument("-o", "--outfile", required=False) | |
parser.add_argument("-a", "--auto-open", required=False, action="store_true") | |
args = parser.parse_args() | |
with open(args.input_file, "rb") as f: | |
file_bytes = f.read() | |
padding_bytes = len(file_bytes) % args.width | |
height = math.ceil(len(file_bytes) / args.width) | |
pgm_header = f"P5 {args.width} {height} 255\n" | |
pgm_data = file_bytes + bytearray([255 for _ in range(padding_bytes)]) | |
auto_open = args.auto_open | |
file_out = args.outfile | |
if not file_out: | |
file_out = "/tmp/" + random_filename() + ".pgm" | |
auto_open = True | |
with open(file_out, "wb") as f: | |
f.write(bytearray(pgm_header, "ascii")) | |
f.write(pgm_data) | |
if auto_open: | |
subprocess.call(("xdg-open", file_out)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment