代码
package cn.itcast.web.verificationCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 100;
int height = 50;
//创建一对象,验证码图片对象
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2.美化图片
Graphics g = image.getGraphics();//画笔对象
g.setColor(Color.PINK);//设置画笔颜色
g.fillRect(0,0,width,height);
//画验证码的边框
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);
String str="ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
Random ran = new Random();
//生成随机角标并获取字符
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
char c = str.charAt(index);
g.drawString(c+"",i*20,height/2);
}
//画线
for (int i = 0; i < 6; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//3.将图片输出到界面展示
ImageIO.write(image,"jpg",resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
相关类
Class BufferedImage
包位置:
java.lang.Object
java.awt.Image
java.awt.image.BufferedImage
//继承关系
public class BufferedImage
extends Image
implements WritableRenderedImage, Transparency
BufferedImage类描述了一个 Image与访问图像数据缓冲区。一个 BufferedImage是由一个 ColorModel和Raster图像数据。
在 Raster的 SampleModel数量和类型的乐队必须匹配的数量和类型的 ColorModel要求代表它的颜色和alpha分量。
所有的 BufferedImage对象的左上角坐标(0, 0)。任何 Raster用来构建一个 BufferedImage必须有X = 0和迷你= 0。
这类依赖于数据的读取和Raster设置方法,并对ColorModel颜色表征方法。