EasyCaptcha/src/main/java/com/wf/captcha/SpecCaptcha.java

102 lines
2.8 KiB
Java
Raw Normal View History

2018-02-11 14:53:59 +08:00
package com.wf.captcha;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
2018-02-11 14:53:59 +08:00
/**
* png格式验证码
* Created by 王帆 on 2018-07-27 上午 10:08.
2018-02-11 14:53:59 +08:00
*/
public class SpecCaptcha extends Captcha {
public SpecCaptcha() {
2018-02-11 14:53:59 +08:00
}
public SpecCaptcha(int width, int height) {
setWidth(width);
setHeight(height);
2018-02-11 14:53:59 +08:00
}
public SpecCaptcha(int width, int height, int len) {
this(width, height);
setLen(len);
2018-02-11 14:53:59 +08:00
}
public SpecCaptcha(int width, int height, int len, Font font) {
this(width, height, len);
setFont(font);
2018-02-11 14:53:59 +08:00
}
2018-02-11 14:53:59 +08:00
/**
* 生成验证码
*
* @param out 输出流
* @return 是否成功
2018-02-11 14:53:59 +08:00
*/
@Override
public boolean out(OutputStream out) {
checkAlpha();
return graphicsImage(textChar(), out);
2018-02-11 14:53:59 +08:00
}
/**
* 生成验证码图形
*
* @param strs 验证码
* @param out 输出流
* @return boolean
2018-02-11 14:53:59 +08:00
*/
private boolean graphicsImage(char[] strs, OutputStream out) {
boolean ok;
try {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
2018-02-11 14:53:59 +08:00
AlphaComposite ac3;
Color color;
2018-02-11 14:53:59 +08:00
int len = strs.length;
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 随机画干扰的圆圈
for (int i = 0; i < 15; i++) {
2018-02-11 14:53:59 +08:00
color = color(150, 250);
g.setColor(color);
g.drawOval(num(width), num(height), 5 + num(10), 5 + num(10));
2018-02-11 14:53:59 +08:00
color = null;
}
g.setFont(font);
int h = height - ((height - font.getSize()) >> 1);
int w = width / len;
int size = w - font.getSize() + 1;
// 画字符串
for (int i = 0; i < len; i++) {
2018-02-11 14:53:59 +08:00
ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);// 指定透明度
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);
2018-02-11 14:53:59 +08:00
color = null;
ac3 = null;
}
ImageIO.write(bi, "png", out);
out.flush();
ok = true;
} catch (IOException e) {
2018-02-11 14:53:59 +08:00
ok = false;
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
2018-02-11 14:53:59 +08:00
}
return ok;
}
}