jsp图片验证码

发布时间 2023-03-22 21:09:34作者: xiaoxing~
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ page import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" %>
<%
    //创建随机对象
    Random random=new Random();
    int width=90,height=40;
    //创建图片对象
    BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

    Graphics g=image.getGraphics();
    g.setFont(new Font("Times New Roman",Font.PLAIN,24));
    g.setColor(Color. black);
    g.fillRect(0,0,width,height);

    StringBuilder str=new StringBuilder();
    //获取随机数
    for(int i=0;i<4;i++)
    {
        g.setColor(new Color(random.nextInt(100,200),random.nextInt(100,200),random.nextInt(100,200)));
        str.append(random.nextInt(10));
        g.drawString(str.substring(i),14+i*19,15+random.nextInt(10,20));
    }
    //随机添加画笔
    for(int i=0;i<5;i++)
    {
        g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
        g.drawLine(random.nextInt(0,70),random.nextInt(10,30),random.nextInt(60,100),random.nextInt(10,30));
    }
    //生成
    g.dispose();
    //写入图片对象
    ImageIO.write(image,"JPEG",response.getOutputStream ());
    out.clear();
    out=pageContext.pushBody();
%>