binimg.py

Here's a simple Python script that opens a file and displays it as a png image. Each byte from the input file is represented as a greyscale pixel from 0 to 255. I saw a similar way of doing this by using PGM files and was inspired to write a python script to do the same thing.

Below is a the output of a simple C binary that prints "Hello World!".

The red line at the bottom represents extra space, since the input file couldn't fill the full height*width pixels of the output image.

Usage

usage: binimg.py [-h] [-w WIDTH] [-o OUTNAME] inFile

Read bytes from an input file and output as a PNG image.

positional arguments:
  inFile      The input files to process.

optional arguments:
  -h, --help  show this help message and exit
  -w WIDTH    The width of the output PNG file.
  -o OUTNAME  Name of the output png file. If none is provided then it will
              default to <input filename>.png.

Code

binimg.py

Will get a syntax hilighter someday.

#!/usr/bin/env python

from PIL import Image,ImageDraw
import math
import sys
import argparse

def saveFileAsPng(filename, width, outname):

  fp = open(filename,'rb')
  data = []
  while True:
    piece = fp.read(1)
    if piece == "":
      break # end of file
    data.append(ord(piece))

  fp.close()
  fillColor = (255,0,0)
  fileSize = len(data)

  height = int(math.ceil(float(fileSize)/width))

  img = Image.new('RGB',(width,height))
  drawing = ImageDraw.Draw(img)

  for row in range(height):
    for col in range(width):
      #check to see if out of bounds
      byteNum = (row*width)+col
      color = fillColor
      if byteNum < len(data):
        color = (data[byteNum],data[byteNum],data[byteNum])

      drawing.point([(col,row)],color)

  img.save(outname, 'PNG')

def main():
  #get arguments
  parser = argparse.ArgumentParser(description='Read bytes from an input file and output as a PNG image.')
  parser.add_argument('files', metavar='inFile', type=str,
                    help='The input files to process.')
  parser.add_argument('-w', dest='width', type=int, default=512,
                    help='The width of the output PNG file.')
  parser.add_argument('-o', dest='outname', type=str,
                    help='Name of the output png file. If none is provided then it will default to <input filename>.png.')
  args = parser.parse_args()

  outname = args.outname
  if not outname:
    outname = '{}.png'.format(args.files)

  saveFileAsPng(args.files, args.width, outname)

if __name__ == '__main__':
  main()