- package ytu.edu.checkcode;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Random;
- import javax.imageio.ImageIO;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ImageServlet extends HttpServlet {
- private static final int WIDTH =120;
- private static final int HIGHT=35;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //创建
- BufferedImage bufferedimage=new BufferedImage(WIDTH, HIGHT, BufferedImage.TYPE_INT_RGB);
- //获取
- Graphics g=bufferedimage.getGraphics();
- //设置背景色
- setBackground(g);
- //设置边框
- setBorder(g);
- //设这干扰线
- drawRandomLine(g);
- //写随机数
- String checkcode=drawRandomNum((Graphics2D)g);//强制转换
- request.getSession().setAttribute("checkcode", checkcode);
- //将图形写给浏览器
- response.setContentType("image/jpeg");
- ImageIO.write(bufferedimage, "jpg", response.getOutputStream());
-
- }
-
- private String drawRandomNum(Graphics2D g) {
- g.setColor(Color.GRAY);
- g.setFont(new Font("宋体", Font.BOLD, 20));
- char[] chars={'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
- 'P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9'};
- int x=10;
- StringBuffer sb=new StringBuffer();
- for(int i=0;i<4;i++){
- int degree=new Random().nextInt()%30;//旋转的度数
- int index=new Random().nextInt(chars.length);
- String s=chars[index]+"";
- sb.append(s);
- g.rotate(degree*Math.PI/180, x, 20);
- g.drawString(s, x, 20);
- g.rotate(-degree*Math.PI/180, x, 20);//清除旋转不让其影响下一次旋转
-
- x=x+30;
- }
- return sb.toString();
-
- }
- private void drawRandomLine(Graphics g) {
- g.setColor(Color.GREEN);
-
- for(int i=0;i<=10;i++){
- int x1=new Random().nextInt(WIDTH);
- int y1=new Random().nextInt(HIGHT);
- int x2=new Random().nextInt(WIDTH);
- int y2=new Random().nextInt(HIGHT);
- g.drawLine(x1, y1, x2, y2);
- }
-
- }
- private void setBorder(Graphics g) {
- g.setColor(Color.BLUE);
- g.drawRect(1, 1, WIDTH-2, HIGHT-2);
-
-
- }
- private void setBackground(Graphics g) {
- g.setColor(Color.WHITE);
- g.fillRect(0, 0, WIDTH,HIGHT);
-
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
复制代码 这是个servlet 直接访问就能产生验证码希望对你有帮助 |