优化验证码的效果和干扰

This commit is contained in:
synchronized
2018-07-27 15:11:34 +08:00
parent a548f7af0b
commit 67409112a7
8 changed files with 204 additions and 128 deletions

View File

@@ -1,9 +1,6 @@
package com.wf.captcha;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@@ -59,30 +56,31 @@ public class SpecCaptcha extends Captcha {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
AlphaComposite ac3;
Color color;
int len = strs.length;
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 随机画干扰的圆圈
for (int i = 0; i < 15; i++) {
color = color(150, 250);
g.setColor(color);
g.drawOval(num(width), num(height), 5 + num(10), 5 + num(10));
color = null;
// 随机画干扰线
for (int i = 0; i < 12; i++) {
int x1 = num(-10, width - 10);
int y1 = num(5, height - 5);
int x2 = num(10, width + 10);
int y2 = num(2, height - 2);
g.setColor(color(150, 250));
g.setStroke(new BasicStroke(1.3f));
g.drawLine(x1, y1, x2, y2);
// 画干扰圆圈
g.setColor(color(100, 250));
g.drawOval(num(width), num(height), 5 + num(25), 5 + num(25));
}
g.setFont(font);
g.setFont(new Font(font.getFontName(), Font.ITALIC, font.getSize()));
int h = height - ((height - font.getSize()) >> 1);
int w = width / len;
int size = w - font.getSize() + 1;
// 画字符串
for (int i = 0; i < len; i++) {
ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);// 指定透明度
ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.75f);// 指定透明度
g.setComposite(ac3);
color = new Color(20 + num(110), 20 + num(110), 20 + num(110));// 对每个字符都用随机颜色
g.setColor(color);
g.drawString(String.valueOf(strs[i]), (width - (len - i) * w) + size, h - 4);
color = null;
ac3 = null;
g.setColor(new Color(20 + num(110), 20 + num(110), 20 + num(110)));
g.drawString(String.valueOf(strs[i]), (width - (len - i) * w) + (w - font.getSize()) + num(7, 11), h - num(2, 6));
}
ImageIO.write(bi, "png", out);
out.flush();