import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.Random;
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.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yitong.commons.model.SessConsts;
@Controller
public class ImageCode {
private Logger logger = Logger.getLogger(this.getClass());
private final int width = 60;
private final int height = 20;
private final int codeCount = 4;
private final int x = width / (codeCount + 1);
private final int fontHeight = height - 2;
private final int codeY = height - 4;
final char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
@RequestMapping("/xxxx/xxxxxxx")
public void execute(HttpServletRequest request, HttpServletResponse response) {
try {
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
Random random = new Random();
buffImg = g.getDeviceConfiguration().createCompatibleImage(width,
height, Transparency.TRANSLUCENT);
g.dispose();
g = buffImg.createGraphics();
// g.setColor(Color.WHITE);
// g.fillRect(0, 0, width, height);
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
g.setFont(font);
g.setColor(Color.BLACK);
for (int i = 0; i < 8; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
for (int i = 0; i < codeCount; i++) {
String strRand = String
.valueOf(codeSequence[random.nextInt(10)]);
red = random.nextInt(100);
green = random.nextInt(155);
blue = random.nextInt(100);
g.setColor(new Color(155 + red, green, 155 + blue));
g.drawString(strRand, (i + 1) * x, codeY);
randomCode.append(strRand);
}
HttpSession session = request.getSession();
session.setAttribute(SessConsts.IMG_CODE, randomCode.toString());
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/png");
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(buffImg, "png", sos);
// sos.close();
sos.flush();
} catch (Exception e) {
logger.error("error", e);
}
}
}