LoginSignup
9
9

More than 5 years have passed since last update.

画像テキストをまとめて生成

Posted at

最近ではCSSのブラウザ対応も良くなり、プレーンなテキストでも十分な表現力を持ったから、Webコンテンツでテキストを画像化しないほうが良いと思っています。

けど、案件によってはデータベースで管理しているようなテキスト情報もすべて画像にしたいという要望を避けられないこともありますよね。

Adobe製品でチクチクとひとつひとつ処理しても良いんですが、
すぐに工数オーバするし、色やサイズ変更が後から発生すると気を失いそうになるのでコマンドラインツールをつくりました。

JSONファイルで文字サイズやフォントを指定してImageMagickのコマンド呼び出しているだけですが、ImageMagickとても便利ですね。
JSONファイルの読み込みやコマンド実行はpythonを使っていますが、単純な処理なので言語は何でも良いと思います。

{
    "sets": [
        {
            "font": "/Library/Fonts/ヒラギノ明朝 Pro W6.otf",
            "size": "23",
            "color": "#000",
            "convert": [
                {
                    "label": "タイトル画像1",
                    "imgpath": "img/txt_title1.png"
                }, {
                    "label": "タイトル画像2",
                    "imgpath": "img/txt_title2.png"
                }
            ]
        }, {
            "size": "29",
            "font": "/Library/Fonts/ヒラギノ角ゴ Pro W6.otf",
            "color": "#EA5304",
            "convert": [
                {
                    "label": "0123456789",
                    "imgpath": "img/num_0123456789.png"
                }, {
                    "label": "9876543210",
                    "imgpath": "img/num_9876543210.png",
                    "color": "#f33"
                }
            ]
        }
    ]
}
#!/usr/bin/python
# -*- encoding: utf-8 -*-

import json, argparse, commands

parser = argparse.ArgumentParser(
    description='Generate image text from json file.'
)
parser.add_argument(
    'conf_file',
    nargs='?',
    default='config.json',
    help='config file'
)

args = parser.parse_args()

# Load config file
f = open(args.conf_file, "rU")
loaded = json.load(f)
f.close()

for set in loaded['sets']:
    font = set.get('font', '');
    size = set.get('size', '30');
    label = set.get('label', 'undefined');
    background = set.get('background', 'None');
    color = set.get('color', '#000');
    imgpath = set.get('imgpath', 'undefined.png');
    for convert in set['convert']:
        font = convert.get('font', font);
        size = convert.get('size', size);
        label = convert.get('label', label);
        background = convert.get('background', background);
        color = convert.get('color', color);
        imgpath = convert.get('imgpath', imgpath);
        conv_cmd = u'convert -background %s -fill "%s" -font "%s" -pointsize %s label:"%s" %s' % (background, color, font, size, label, imgpath)
        print conv_cmd
        out = commands.getoutput(conv_cmd.encode('utf_8'))
        print out
print

画像化の要件があまりにも多い場合は同一サーバ内に画像化APIを構築しても良いかもしれないです。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9