Java生成验证码

来源:互联网 发布:transmac制作mac安装盘 编辑:程序博客网 时间:2024/06/07 05:48

效果如下图:



详细代码如下:

package gz.itcast.shopsys.util;import java.awt.Color;import java.awt.Font;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.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.xml.ws.Response;import org.junit.runner.Request;//生成验证码public class ValidateCodeUtil extends HttpServlet {//生成随机数Random rd = new Random();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//1、生成一张图片int width = 100;int height =60;BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);//2、图片背景改成灰色//拿到画笔Graphics graphics = img.getGraphics();//设置画笔颜色graphics.setColor(Color.gray);//用画笔填充一个矩形graphics.fillRect(0, 0, width, height);//调画笔颜色来写数字graphics.setColor(Color.BLUE);String rds ="";for(int i =1; i<= 4; i++){//生成四个不大于10的数(0-9)int nextInt = rd.nextInt(10);rds += nextInt;}//改变字体graphics.setFont(new Font("宋体", Font.ITALIC, 35));//用画笔将字符串写出来graphics.drawString(rds,10, 40);//随机生成多条线段来进行干扰for(int i =1; i <=35; i++){//为每条线段赋值颜色graphics.setColor(alterColor());int x1 = rd.nextInt(100);int x2 = rd.nextInt(100);int y1 = rd.nextInt(60);int y2 = rd.nextInt(60);graphics.drawLine(x1, y1, x2, y2);}ImageIO.write(img, "gif", response.getOutputStream());}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doGet(req, resp);}public Color alterColor(){int r = rd.nextInt(256);int g = rd.nextInt(256);int b = rd.nextInt(256);Color  c = new Color(r,g,b);return c;}}


0 0
原创粉丝点击