- 演示
- 定义图片对象
- 设置画笔
- 画边框
- 写文字
- 验证码随机
- 随机干扰线
- 让图片在指定的位置显示
- 点击换图
- 让文字变大
- 实战
演示代码字节流
定义图片对象 设置画笔x y 设置位置
画边框注意 右 和 下 没有边框 ,原因是矩形打了,变小一点就可以了
这个是验证码的servlet
package servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/verifyCode")
public class VerifyCode extends HttpServlet {
private Random random = new Random();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取字节输出流的对象
ServletOutputStream outputStream = resp.getOutputStream();
//获得一个图片对象
int width = 100;
int height = 50;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//图片背景
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.BLUE);
graphics.fillRect(0, 0, width, height);
// 验证码内边框
graphics.setColor(Color.RED);
graphics.drawRect(0, 0, width - 1, height - 1);
// 获取验证码内容
String code = getCode();
// 存到 session
HttpSession session = req.getSession();
session.setAttribute("code",code);
// 文字变大了,y 坐标就要变
int y = 30;
graphics.setColor(Color.YELLOW);
// 让文字变大
graphics.setFont(new Font("simhei", Font.PLAIN, 24));
for (int i = 0; i < code.length(); i++) {
String c = code.charAt(i) + "";
int n = i + 1;
int x = n * 20;
graphics.drawString(c, x, y);
}
// 干扰线
graphics.setColor(Color.RED);
for (int i = 0; i < 20; i++) {
//生成坐标
// 横坐标
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
// 纵坐标
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
//画线
graphics.drawLine(x1, y1, x2, y2);
}
// 返回给游览器
ImageIO.write(bufferedImage, "jpg", outputStream);
}
private String getCode() {
// 内容池
String content = "abcdABCDEFG123456789";
String code = "";
for (int i = 0; i < 4; i++) {
int idx = random.nextInt(content.length());
char c = content.charAt(idx);
code += c;
}
return code;
}
}
下面是页面
<%--
Created by IntelliJ IDEA.
User: SSOA
Date: 2022/6/9
Time: 13:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
尤洪





