Saturday, April 18, 2009

Making pictures of files

Hello world!

I made a little python tool and wanted to share it. It's a neat little tool to visualize binary data in a graphical form. It's really interesting to look at different types of files.


#!/usr/bin/python
#"Copyright 2009 Bryan Harris"
#
#This file is part of bin2bmp.py.
#
# bin2bmp.py is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# bin2bmp.py is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with bin2bmp.py; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

import Image
import os
import sys
import array

if len(sys.argv)<3:
    print "usage:", sys.argv[0], "filename width"
    exit(-1)


try:
    width=int(sys.argv[2])
except:
    print "The second argument, "+sys.argv[2]+", does not appear to be an integer!"


tmpfile = sys.argv[1]
filename = os.path.split(sys.argv[1])[1]
try:
    fileobj = open(tmpfile, mode='rb')
except:
    print "Can't open "+sys.argv[1]+" for some reason."
    exit(-1)

size=os.path.getsize(tmpfile)
buffer=array.array('B',fileobj.read())
buffer.reverse()
print filename+':',size,"bytes"
chunks=size/3
black=(0,0,0)
white=(255,255,255)
im = Image.new("RGB",(width,int(chunks/width)+1),black)
for i in range(chunks):
    x=i%(width)
    y=i/(width)
    RGB=(buffer.pop(),buffer.pop(),buffer.pop())
    #if i<20:print RGB
    im.putpixel((x,y),RGB)
im.save(filename+'.bmp',"BMP")

No comments:

Post a Comment