User:Xyb/生成汉字图片

維基詞典,自由的多語言詞典

说明[编辑]

我编写了一个 shell 脚本,用来生成指定汉字的图片:

准备[编辑]

脚本的执行需要 Unix/Linux 环境,在 Windows 里可以使用 Cygwin。

需要安装

  • iconv 套件
  • imagemagick 套件
  • 文鼎科技提供的简体中文楷体字体 gkai00mp.ttf。通常放在/usr/share/fonts/下的某个目录中,如果你的系统上没有,可以下载 http://www.arphic.net/tw/download/gkai00mp.zip ,解压缩出 gkai00mp.ttf 文件并放到脚本所在目录。如果你和我一样使用 GNU/Linux Debian,可以直接执行 apt-get install ttf-arphic-gkai00mp 来安装该字体。
Cygwin[编辑]

如果你想在 Windows 上使用这个脚本,推荐用 Cygwin。 可以到 http://www.cygwin.com/ 下载并安装,必须安装的套件有:

  • Lib :: libiconv
  • Graphic :: imagemagick
  • 同样也需要文鼎的字体文件

使用[编辑]

把一个汉字作为脚本的参数传入,例如生成“时”字的图片:

./hanzi.sh 时

脚本将在当前目录生成一个名为 u97E6.png 的文件,这是字符“u”+“时”字的 unicode 代码 + “.png”文件后缀名。

生成图片的尺寸为 100x100。

脚本的代码[编辑]


#!/bin/sh
# xyb76@sina.com

# 用于中文维基百科词典的汉字图片生成,适用于简体中文。
# 使用 imagemagick 工具套件(www.imagemagick.org),运行于 GNU/Linux Debian
# 使用文鼎科技GPL的 arphic 简体中文楷体字体(可到 http://www.arphic.com.tw/
# 免费下载: http://www.arphic.net/cn/service/resource.htm)
# 修改 convert 命令中使用的字体名称就可以使用繁体或宋体字体。

# 如果需要在 Windows 中运行,推荐使用 Cygwin 套件: http://www.cygwin.com/
# 注意:
#   1. 安装 Lib :: libiconv
#   2. 安装 Graphic :: imagemagick
# 如果出现汉字输入问题,请参考:
# http://worldhello.net/wiki/C/Cygwin.htm?Cygwin#_3_5

if [ x"$1" = x ]; then
    echo 'Please give me a chinese word.'
    exit 1
fi

HANZI=$1

# check iconv
echo | iconv
if [ $? != 0 ]; then
    echo 'iconv not exists'
    uname -a | grep CYGWIN >& /dev/null
    if [ $? = 0 ]; then
        echo 'Please install package Lib:libiconv on Cygwin.'
    fi
    exit 1
fi

# check font
if [ -f /usr/share/fonts/truetype/arphic/gkai00mp.ttf ]; then
    FONT=/usr/share/fonts/truetype/arphic/gkai00mp.ttf
elif [ -f ./gkai00mp.ttf ]; then
    FONT=./gkai00mp.ttf
else
    echo 'Font gkai00mp.ttf is not exists. please download it from:'
    echo '  http://www.arphic.net/tw/download/gkai00mp.zip'
    exit 1
fi

# check convert
convert >& /dev/null
if [ $? != 0 ]; then
    echo convert not exists
    uname -a | grep CYGWIN >& /dev/null
    if [ $? = 0 ]; then
        echo 'Please install package Graphic:imagemagick on Cygwin.'
    else
        echo 'Please install ImageMagick(www.imagemagick.org).'
    fi
    exit 1
fi

HANZI=`echo $HANZI|iconv -f gbk -t utf-8`
#FILENAME=u`echo $HANZI|od -x|head -1|awk '{print $2}'|tr 'a-z' 'A-Z'`.png
#上面语句有问题,用ucs2编码来生产Unicode 码,
#修改如下:
#add by vaccine
HANZIu=`echo $HANZI|iconv -f gbk -t ucs2`
FILENAME=u`echo $HANZIu|od -x|head -1|awk '{print $2}'|tr 'a-z' 'A-Z'`.png
#end 
echo $FILENAME

convert -size 100x100 xc:white -gravity Center \
  -fill black -draw "text 0,0 '"$HANZI"'" \
  -pointsize 100 -font $FONT \
  "$FILENAME"