使用者: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"