1后台编码:
public void drawImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
String imgpath = request.getServletContext().getRealPath("/img/code.png");
ImageIcon imgOBJ = new ImageIcon(imgpath);
BufferedImage img_bf = new BufferedImage(130, 50, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img_bf.getGraphics();
g.drawImage(imgOBJ.getImage(), 0, 0, null);
String str = "ABCDEFGHIJKMLOPQRSTUVXWYZabcdefghijkmlopqrstuvxzyw123456789";
Random rd = new Random();
g.setFont(new Font("宋体",Font.BOLD,40));
int x1code = 0;
for (int i = 0; i < 4; i++) {
g.setColor(Color.getHSBColor(rd.nextFloat(), rd.nextFloat(), rd.nextFloat()));
g.drawString(str.charAt(rd.nextInt(str.length()))+"", (x1code+=20), 35);
}
g.setColor(Color.green);
int x1,x2,y1,y2;
for (int i = 0; i < 4; i++) {
x1 = rd.nextInt(130);
x2 = rd.nextInt(130);
y1 = rd.nextInt(50);
y2 = rd.nextInt(50);
g.drawLine(x1, y1, x2, y2);
g.drawOval(x1, y1, 10, 10);
}
//String saveImgPath = request.getServletContext().getRealPath("/img");
ImageIO.write(img_bf, "jpg", response.getOutputStream());
}
2.前台页面接收,展示;
<span>请输入验证码:</span><input type="text" name="code"/><img alt="" src="servlet/ImgUpLoad?op=drawImg" οnclick="changeImg(this)">