imageMagick 安装
官网下载页下载,安装完成后得到 convert 命令。若是 Mac,可以直接使用下面的命令
brew install imagemagick
生成一个验证码
$ convert -size 290x70 xc:white -bordercolor black -border 5
-fill black -stroke black -strokewidth 1 -font TimesNewRoman -pointsize 40
-draw "translate -116,-5 skewX 37 gravity center text 0,0 'a'"
-draw "translate -73,-4 skewX -20 gravity center text 0,0 's'"
-draw "translate -26,8 skewX 28 gravity center text 0,0 'd'"
-draw "translate 27,5 skewX 27 gravity center text 0,0 'f'"
-draw "translate 75,-3 skewX -7 gravity center text 0,0 'q'"
-draw "translate 118,7 skewX 36 gravity center text 0,0 'k'"
-fill none -strokewidth 5
-draw "bezier 22.4,58 68.6,56 129.1,50 180.8,58"
-draw "polyline 174.2,58 234.7,38 280.9,56"
-resize 100%
./test.jpg
Node 执行下列命令来生成一张验证码
const exec = require('child_process').exec;
const command = `
convert -size 290x70 xc:white -bordercolor black -border 5
-fill black -stroke black -strokewidth 1 -font TimesNewRoman -pointsize 40
-draw "translate -116,-5 skewX 37 gravity center text 0,0 'a'"
-draw "translate -73,-4 skewX -20 gravity center text 0,0 's'"
-draw "translate -26,8 skewX 28 gravity center text 0,0 'd'"
-draw "translate 27,5 skewX 27 gravity center text 0,0 'f'"
-draw "translate 75,-3 skewX -7 gravity center text 0,0 'q'"
-draw "translate 118,7 skewX 36 gravity center text 0,0 'k'"
-fill none -strokewidth 5
-draw "bezier 22.4,58 68.6,56 129.1,50 180.8,58"
-draw "polyline 174.2,58 234.7,38 280.9,56"
-resize 100%
./test.jpg
`;
new Promise((resolve, reject) => {
exec(command, function(err) {
if (err) {
reject(err);
}
resolve({
code: text,
path: url,
});
});
});
生成一张交错的黑白交错的网格背景
生成一个张黑白交错的网格背景,并且平铺它。
$ convert -size 20x20 xc:white
-fill black
-draw "rectangle 0,0 10,10 rectangle 10,10 20,20"
./bg.jpg
$ composite -tile bg.jpg -size 290x70 xc:none test.jpg
在某张背景图上写入验证码文字
$ convert -size 290x70 -strip xc:none ./test.jpg -gravity center
-composite
-bordercolor black -border 5
-fill transparent -stroke black -strokewidth 1
-font Verdana -pointsize 50
-draw "translate -73,-6 skewX -3 gravity center text 0,0 '5'"
-draw "translate -49,-4 skewX 16 gravity center text 0,0 '3'"
-draw "translate -11,-7 skewX 23 gravity center text 0,0 '9'"
-draw "translate 18,8 skewX 7 gravity center text 0,0 '3'"
-draw "translate 47,-5 skewX -20 gravity center text 0,0 '6'"
-draw "translate 77,-6 skewX -8 gravity center text 0,0 '4'"
-fill none -stroke black -strokewidth 5
-draw "bezier 65,28 91,32 133,26"
-draw "polyline 133,26 165,56 212,30 245,28"
./test_text.jpg
灰度化
convert in.png -grayscale Rec709Luma gray.png
Rec709Luma 是一种灰度算法。
二值化
常用于破解验证码,提交给 OCR 识别
# 若用原图
convert in.png -monochrome out.png
# 若用灰度图,threshold代表二值化程度
convert gray.png -threshold 55% gray_out.png