优化验证码效果

This commit is contained in:
whvcse@foxmail.com
2018-08-09 15:50:40 +08:00
parent 7defc7e727
commit 27af06eff5
9 changed files with 139 additions and 85 deletions

View File

@@ -32,7 +32,7 @@ public class GifCaptcha extends Captcha {
@Override
public boolean out(OutputStream os) {
checkAlpha();
boolean ok = false;
boolean ok;
try {
char[] rands = textChar(); // 获取验证码数组
GifEncoder gifEncoder = new GifEncoder();
@@ -77,35 +77,27 @@ public class GifCaptcha extends Captcha {
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
// 抗锯齿
g2d.setFont(font);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1.3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
// 画干扰圆圈
drawOval(4, g2d);
// 随机画干扰线
for (int i = 0; i < num(5, 12); i++) {
g2d.setStroke(new BasicStroke(1.1f + RANDOM.nextFloat() / 2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2d.setColor(color(150, 250));
int x1 = num(-10, width - 10);
int y1 = num(5, height - 5);
int x2 = num(10, width + 10);
int y2 = num(2, height - 2);
g2d.drawLine(x1, y1, x2, y2);
// 画干扰圆圈
g2d.setColor(color(100, 250));
g2d.drawOval(num(width), num(height), 5 + num(25), 5 + num(25));
}
drawLine(2, g2d);
// 画验证码
int hp = (height - font.getSize()) >> 1;
int h = height - hp;
int w = width / strs.length;
//int sp = (w - font.getSize()) / 2;
int sp = (w - font.getSize()) / 2;
for (int i = 0; i < strs.length; i++) {
AlphaComposite ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha(flag, i));
g2d.setComposite(ac3);
g2d.setColor(fontcolor[i]);
// 计算坐标
int x = i * w + num(6);
int y = h - num(2, 8);
if (x < 0) {
x = 0;
int x = i * w + sp + num(3);
int y = h - num(3, 6);
// 调整溢出的字
if (x < 8) {
x = 8;
}
if (x + font.getSize() > width) {
x = width - font.getSize();
@@ -116,6 +108,7 @@ public class GifCaptcha extends Captcha {
if (y - font.getSize() < 0) {
y = font.getSize();
}
g2d.setFont(font.deriveFont(num(2) == 0 ? Font.PLAIN : Font.ITALIC));
g2d.drawString(String.valueOf(strs[i]), x, y);
}
g2d.dispose();