package com.youself.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import cn.ucfgroup.oauth.service.utils.RandomUtil; /** * @ClassName: CaptchaController * @Description: 图片验证码服务 * @author: admin * @date: 2013年12月24日 下午5:26:37 */ @Controller @RequestMapping("/captcha") public class CaptchaController extends BaseController { private int width = 146; private int height = 48; private int codeLength = 4; private int codeX = (width - 4) / (codeLength + 1); private int codeY = height - 7; /** * @param request 上下文request * @param response 上下文response */ @RequestMapping(value = "/get", method = RequestMethod.GET) public void getCaptcha(HttpServletRequest request, HttpServletResponse response) { String randomCode = RandomUtil.randomFixedLengthChars(codeLength); //生成随机验证码的帮助类 char codes[] = randomCode.toCharArray(); // 定义图像buffer BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gd = buffImg.createGraphics(); // 将图像填充为白色 gd.setColor(Color.WHITE); gd.fillRect(0, 0, width, height); // 建立字体,字体的大小应该根据图片的高度来定。 Font font = new Font("Fixedsys", Font.PLAIN, height - 10); // 设置字体 gd.setFont(font); // 画边框。 gd.setColor(new Color(221, 221, 221)); gd.drawRect(0, 0, width - 1, height - 1); for (int i = 0; i < codeLength; i++) { gd.setColor(Color.BLUE); gd.drawString(String.valueOf(codes[i]), (i + 1) * codeX, codeY); } // 将四位数字的验证码保存到Session中。 HttpSession session = request.getSession(); session.setAttribute("captchaCode", randomCode); // 禁止图像缓存。 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); // 将图像输出到Servlet输出流中。 ServletOutputStream sos; try { sos = response.getOutputStream(); ImageIO.write(buffImg, "jpeg", sos); sos.close(); } catch (IOException e) { e.printStackTrace(); } } }