Thursday, June 30, 2011

python example (jpeg timestamp)

This is a combination usage of:
iterator
callback
yield
image processing

Created/updated by BA43B09F0725,qunshan@newsmth

import os, sys, time
import Image, ImageDraw, ImageFont

def findfiles(path, *callbacks):
for root, dirs, names in os.walk(path):
for name in names:
filename = os.path.join(root, name)
info = tuple(x(filename) for x in callbacks)
yield (filename,)+info

def addString(filename, timestr):
font = ImageFont.truetype(os.path.join(os.environ['windir'], 'Fonts', 'AGENCYB.TTF'), 108)
im = Image.open(filename)
x, y = im.size
draw=ImageDraw.Draw(img)
#draw.ink = 0 + 255*256 + 0*256*256
draw.text((x-640,y-128), timestr, font=font)
img.save(filename)

def addTimeString(filename, mtime):
timestr = time.strftime("%Y-%m-%d %H:%M", time.localtime(mtime))
addString(filename, timestr)
os.utime(filename, (time.time(), mtime))

if __name__ == '__main__':
for filename, mtime in findfiles(sys.argv[1], os.path.getmtime):
if filename.lower().endswith(('.jpg', '.jpeg')):
addTimeString(filename, mtime)

No comments: