Java图片验证码
2021-01-04 18:29
标签:随机验证码 draw 生产 type 填充 join 验证 value 内存 图像验证码的实现 结束! Java图片验证码 标签:随机验证码 draw 生产 type 填充 join 验证 value 内存 原文地址:https://www.cnblogs.com/wccw/p/12983922.htmlpackage com.ccw.utils;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ImageVerCodeUtil {
/**
* 创建图形验证码
* @param width 绘制图片的宽度
* @param height 绘制图片的高度
* @return 返回map{"code":验证码,"image":创建的图像}
*/
public static Map getVerificationCode(int width, int height){
Random random = new Random();
// 设置页面不缓存
//response.setHeader("Pragma", "No-cache");
//response.setHeader("Cache-Control", "no-cache");
//response.setDateHeader("Expires", 0);
// 在内存创建图像
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// 获取图像上下文
Graphics2D graphics = (Graphics2D) image.getGraphics();
// 设置图像背景色
graphics.setColor(new Color(220,220,220));//设置颜色
graphics.fillRect(0,0,width,height);//填充衍射
// 设定边框颜色
// graphics.setColor(new Color(210,210,250));
// graphics.drawRect(0,0,width - 1,height - 1);
// 产生随机线条
//创建一个供画笔选择线条粗细的对象
BasicStroke bs = new BasicStroke(3,BasicStroke.CAP_SQUARE,BasicStroke.JOIN_ROUND);
graphics.setStroke(bs);
for (int i=0;i){
graphics.setColor(new Color(random.nextInt(100)+150,random.nextInt(100)+150,random.nextInt(100)+150));
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x,y,x1,y1);//画线
int dx = random.nextInt(width);
int dy = random.nextInt(height);
graphics.drawLine(dx,dy,dx,dy);//画点
}
// 生产随机验证码
String checkCode = String.valueOf(random.nextInt(8999)+1000);
// 写入图像
for (int i =0;i ){
graphics.setColor(new Color(random.nextInt(100)+70,random.nextInt(100)+70,random.nextInt(100)+70));
graphics.setFont(new Font("Aria", Font.BOLD,24));
// 设置随机旋转
AffineTransform transform = new AffineTransform();
transform.setToRotation((random.nextInt(3) - 1) * random.nextDouble(),(24 * i)+8,18);//(旋转角度,围绕坐标x,围绕坐标y)
graphics.setTransform(transform);
graphics.drawString(String.valueOf(checkCode.charAt(i)),(23 * i)+8,28);
}
// 输出图像
graphics.dispose();
Map