package springbootdemo.demo.util;
import com.sun.deploy.net.HttpResponse;
import org.springframework.http.HttpRequest;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
/**图形验证码工具类
* @author
* @date 2019/8/20 17:54
*/
public class GraphicVerificationCodeUtil {
/*生成的图片宽度*/
private static final int WIDTH=150;
/*图片高度*/
private static final int HEIGTH=50;
/*验证码字符个数*/
private static final int codeCount=5;
/* 干扰数*/
private static final int radomLine=5;
/*设置背景颜色*/
public static void setBackgroundColor(Graphics2D g){
//设置画笔颜色
g.setColor(Color.WHITE);
/*填充大小指定的矩形*/
g.fillRect(0,0,WIDTH,HEIGTH);
}
public static void addRandomLine(Graphics2D g){
Random random=new Random();
/*设置干扰线*/
for (int i = 0; i <radomLine ; i++) {
int x1=random.nextInt(WIDTH);
int y1=random.nextInt(HEIGTH);
int x2=random.nextInt(WIDTH);
int y2=random.nextInt(HEIGTH);
//设置干扰线随机颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.drawLine(x1,y1,x2,y2);
}
}
public static void provideImg() throws IOException {
/*生成一张图片*/
BufferedImage bufferedImage=new BufferedImage(WIDTH,HEIGTH,BufferedImage.TYPE_INT_BGR);
/*为图片构建一支画笔*/
Graphics2D g=(Graphics2D)bufferedImage.getGraphics();
//设置背景
setBackgroundColor(g);
//添加干扰线
addRandomLine(g);
//随机码
String randomCode=setRandomCode(g);
FileOutputStream fileOutputStream=new FileOutputStream("E:/hello.png");
ImageIO.write(bufferedImage,"png",fileOutputStream);
}
/**
* @description: 设置随机验证码
* @author:
* @date: 2019/8/20
* @param null:
* @return:
*/
public static String setRandomCode(Graphics2D g){
String randomCode="";
/*设置字体颜色*/
g.setColor(new Color(20,20,20));
/*设置字体*/
g.setFont(new Font("宋体",Font.BOLD,HEIGTH-30));
//随机字符
String randomStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyz";
Random random=new Random();
// 定义一个下标
int index;
// 定义X轴变量
int x = WIDTH/10;
for (int i = 0; i <codeCount ; i++) {
index=random.nextInt(randomStr.length());
// 获取index索引处的字符
char c = randomStr.charAt(index);
// 将每个字添加到sb中
// String code =c+"";
randomCode = randomCode + c;
// 添加旋转角度 随机角度到-40 ---40度
int angle = random.nextInt(80) - 40;
// 转成弧度
double theta = Math.PI * angle / 180;
// 旋转
// g.rotate(theta, x, 15);
// 画上字符
g.drawString(c + "", x, HEIGTH/2+10);
// 转回来
// g.rotate(-theta, x, 15);
x += WIDTH/5;
}
return randomCode;
}
public static void main(String[] args) {
try {
provideImg();
} catch (IOException e) {
e.printStackTrace();
}
}
}