import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class VerifyCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1 大小
int width = 60;
int height = 30;
// * 基本数据
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
//2 绘制图片 #ff0000 (红绿蓝) 0-255 (00-ff)
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.1 获得画板
Graphics g = image.getGraphics();
//2.2 绘制矩形(默认黑色) --填充
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
//2.3 绘制白色矩形
g.setColor(Color.WHITE);
g.fillRect(1, 1, width-2, height-2);
//2.4 随机4个数字
Random random = new Random();
// * 设置字体
/**#1 提供容器,存放随机字符*/
StringBuilder builder = new StringBuilder();
g.setFont(new Font("宋体", Font.BOLD, 20));
for(int i = 0 ; i < 4 ; i++){
// * 设置颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
// * 随机获得字符串长度一个数字
int index = random.nextInt(data.length());
// * 截取一个字符
String str = data.substring(index, index + 1);
/**#2 缓存字符*/
builder.append(str);
// * 将字符串写入到图片
g.drawString(str, (i+1) * width / 6, 20);
}
/**#3 将缓存随机字符串,缓存到session中*/
String randomStr = builder.toString();
request.getSession().setAttribute("sessionCacheData", randomStr);
//2.5 干扰线
for(int i = 0 ; i < 2 ; i ++){
// * 设置颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
// * 划线
g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
//3 发送图片到浏览器 ,参数1:发送内容, 参数2:扩展名,参数3:发送浏览器流(字节流)
ImageIO.write(image, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
发表吐槽
你肿么看?
既然没有吐槽,那就赶紧抢沙发吧!