javaee验证码

package servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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;

/**
 * Servlet implementation class image
 */
@WebServlet("/image")
public class image extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final int WIDTH = 120;
	private final int HEIGHT= 30;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public image() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
			BufferedImage br = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		
		Graphics2D graphics = (Graphics2D) br.getGraphics();
		
		graphics.setColor(new Color(198,255,255));
		graphics.fillRect(0, 0, WIDTH, HEIGHT);
		
		String base ="1";
		
		Random rand = new Random();
		
	
		graphics.setColor(Color.RED);
		

		graphics.setFont(new Font("黑体", Font.PLAIN, 18));
		int m =18;
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i < 4; i++) {
			
		
			int index = rand.nextInt(base.length());
			
			char charAt = base.charAt(index);
			
		
			int jiaodu = rand.nextInt(60)-30;
			
			double theta = jiaodu*Math.PI/180;
			graphics.rotate(theta,m, 20);
			graphics.drawString(charAt+"", m, 20);
			sb.append(charAt);
			graphics.rotate(-theta,m, 20);
			m+=25;
		}
		request.getSession().setAttribute("checked", sb.toString());
		graphics.setColor(Color.GREEN);
		 
		for (int i = 0; i < 4; i++) {
			
			int x1 = rand.nextInt(WIDTH);
			int x2 = rand.nextInt(WIDTH);
			int y1 = rand.nextInt(HEIGHT);
			int y2 = rand.nextInt(HEIGHT);
			graphics.drawLine(x1, y1, x2, y2);
		}
		
		
		 
		graphics.dispose();
		
		
		 
		ImageIO.write(br, "png", response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值