response 画验证码
Posted 小江
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了response 画验证码相关的知识,希望对你有一定的参考价值。
代码
import java.awt.Color; import java.awt.Font; 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 ValiImage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 150; int height = 50; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); //添加背景颜色 g.setColor(Color.GRAY); g.fillRect(0,0,width,height); //添加边框 g.setColor(Color.black); g.drawRect(0,0,width-1,height-1); //画干扰线 int count = 10; while(count>0) { g.setColor(Color.RED); g.drawLine(RandomNum(0,width), RandomNum(0,height),RandomNum(0,width), RandomNum(0,height)); count--; } //画字体 for(int p = 0 ; p < 4; p++) { g.setColor(new Color(RandomNum(0,255),RandomNum(0,255),RandomNum(0,255))); g.setFont(new Font("黑体",Font.BOLD,20)); g.drawString("中",5+(p*37),25); } ImageIO.write(image,"jpg",response.getOutputStream()); } private Random rand = new Random(); public int RandomNum(int i,int j) { //返回一个大于i小于j的随机数 //return rand.nextInt(j-i)+i; return i+(int)(Math.random()*j); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
以上是关于response 画验证码的主要内容,如果未能解决你的问题,请参考以下文章