Created
July 25, 2022 10:30
-
-
Save kianryan/0749f300b97136dca116180a43b1b4e4 to your computer and use it in GitHub Desktop.
Convert PBM to Bytearray
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
# Convert image to bytes | |
#!/usr/bin/env python | |
import sys | |
import os | |
def main(): | |
if len(sys.argv) != 2: | |
usage() | |
return 2 | |
with open(sys.argv[1], 'rb') as fd: | |
pbm_format = fd.readline().strip() | |
if pbm_format != b'P4': | |
print("ERROR: input file must be binary PBM (type P4)", | |
file = sys.stderr) | |
return 1 | |
pbm_dims = [int(d) for d in fd.readline().strip().split()] | |
pbm_data = fd.read() | |
fbbase = "buf_{0}".format(os.path.basename(sys.argv[1])) | |
fbname = os.path.splitext(fbbase)[0] | |
with sys.stdout as fd: | |
f = "{0} = bytearray({1})\n" | |
fd.write(f.format(fbname, str(pbm_data), pbm_dims[0], pbm_dims[1])) | |
def usage(): | |
print("""usage: {0} PBM_FILE""".format(os.path.basename(sys.argv[0])), | |
file = sys.stderr) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment