javaweb-servlet生成简单的验证码

package com.serv;

import java.awt.Color;
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.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns={"/Servyzm"})
public class Servyzm extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO 自动生成的方法存根
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO 自动生成的方法存根
        Random r = new Random();
        //创建图片缓冲流
        BufferedImage buf = new BufferedImage(70, 25, BufferedImage.TYPE_INT_RGB);
        Graphics g = buf.getGraphics();//获取图片的画布对象
        g.fillRect(0, 0, 70,25);//从左上角开始(0,0)坐标开始填充白色,宽70,高25
        g.setColor(new Color(150,150,150));//指定的是显示的字体的颜色
        String str = r.nextInt(9000)+1000+"";
        g.drawString(str, 20, 20);// drawString(String str, int x, int y)str指的是输出的文本;x,y指的是距离左上角的位置
        for (int i = 0; i < 8; i++) {
            int startx = r.nextInt(120);
            int starty = r.nextInt(30);
            g.setColor(new Color(startx, 232, starty));
            g.drawLine(startx, starty, startx + 10, starty + 10);
        }
        ServletOutputStream out = resp.getOutputStream();// 获取字节流
        ImageIO.write(buf, "jpg", out);
    }
//    public static int getString(){
//        
//    }
}

 运行截图:

 

posted @ 2017-09-20 22:22  烟花盛典  阅读(157)  评论(0编辑  收藏  举报