#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- mode: python;Encoding: utf8n -*- # Last updated: <2013/08/02 16:22:24 +0900> u'''高橋メソッドで画像保存するPythonスクリプト. usage : takahashi_method.py -i textfile takahashi_method.py --help テキストは sjis で記述のこと。 Windows7 x64 + Python 2.6.6 + PIL 1.1.7 で動作確認した。 標準では HGRSGU.TTC (HGP創英角ゴシックUB) を使用。 HGRHM9.TTC (HGP平成明朝体W9) を使うのもいいかもしれない。 フォント指定は絶対パスで指定するべきだが、 Windows上では、警告が出るものの、 フォントファイル名を指定するだけでも動くように見える。 ''' import os import codecs from PIL import Image, ImageDraw, ImageFont from optparse import OptionParser def main(): p = OptionParser(usage="usage: %prog [option]", version="%prog 0.01") p.add_option("--font", help="use TTF filename [default: %default]", metavar="FILE", default='HGRSGU.TTC') p.add_option("--fontsize", help="font size [default: %default]", metavar="INT", default=160) p.add_option("--width", help="image width [default: %default]", metavar="INT", default=1280) p.add_option("--height", help="image height [default: %default]", metavar="INT", default=720) p.add_option("-i", "--input", help="input text file [default: %default]", metavar="FILE", default="mes.txt") p.add_option( "--debug", help="debug", action="store_true") (opts, args) = p.parse_args() sw, sh = int(opts.width), int(opts.height) fnt = ImageFont.truetype(opts.font, int(opts.fontsize), encoding='shift_jis') all_lines = codecs.open(opts.input, 'r', 'shift_jis').read() count = 0 for page in all_lines.split("----"): lines = page.strip().splitlines() im = Image.new('RGB', (sw, sh), 'white') draw = ImageDraw.Draw(im) w, h = draw.textsize(lines[0], fnt) spacing = h / 4 fsize_h = h + spacing y = (sh - (fsize_h * len(lines) - spacing)) / 2 for s in lines: w, h = draw.textsize(s, fnt) draw.text(((sw - w) / 2, y), s, font = fnt, fill='black') y += fsize_h if opts.debug: im.show() else: im.save("%04d.png" % count, 'PNG') count += 1 if __name__ == '__main__': main()