Rcjp's Weblog

September 18, 2006

Image of a Logfile

Filed under: python, utils — rcjp @ 10:57 am

Logfile

I needed some code to create an image which roughly gave an impression of the file contents for a log file analyser I was writing. The following code crudely looks for the shape of letters and draws some dots into a .png file.

import Image, ImageDraw
import os

def drawfilethumb(filename, imagex=80, imagey=200, border=5):
    """Create a png image representing the file"""
    log = []
    log = open(filename).readlines()
    loglen = len(log)

    logimage = Image.new('RGB', (imagex+10,imagey+10), (255,255,255))
    draw = ImageDraw.Draw(logimage)

    maxlen = max(len(x) for x in log)
    xscale = maxlen/float(imagex)
    yscale = loglen/float(imagey)

    y = 0
    while y < imagey and y*yscale < loglen:
        line = log[int(y*yscale)]
        linelen = len(line)
        x = 0
        while x < imagex and x*xscale < linelen:
            ch = line[int(x*xscale)]
            if ch.isupper() or ch.isdigit():
                draw.point([(border+x, border+y), (border+x, border+y-1)], fill=0)
            elif ch in ('t', 'd', 'f', 'h', 'k', 'l', 'b'):
                draw.point([(border+x, border+y), (border+x, border+y-1)], fill=128)
            elif ch in ('q', 'y', 'p', 'g', 'j'):
                draw.point([(border+x, border+y), (border+x, border+y+1)], fill=128)
            else:
                draw.point((border+x, border+y), fill=128)
            x+=1
        y += 4

    del draw
    f, ext = os.path.splitext(filename)
    logimage.save(f+'.png', "PNG")

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: