package com.newcapec.utils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
/**
* Title: ValidateCode.java
* Description: 验证码工具类
*/
public class ValidateCode {
// 图片的宽度。
private int width = 120;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 4;
// 验证码干扰线数
private int lineCount = 30;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg = null;
private char[] codeSequence = { 'A','a', 'B','b', 'C','c', 'D','d', 'E','e', 'F','f', 'g','H','h',
'J','j', 'K','k','L', 'M','m', 'N','n', 'P','p', 'Q','q', 'R','r', 'S','s', 'T', 'U','u', 'V', 'W','w',
'X','x', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
// 生成随机数
private Random random = new Random();
public ValidateCode() {
this.createCode();
}
/**
*
* @param width
* 图片宽
* @param height
* 图片高
*/
public ValidateCode(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
*
* @param width
* 图片宽
* @param height
* 图片高
* @param codeCount
* 字符个数
* @param lineCount
* 干扰线条数
*/
public ValidateCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
this.createCode();
}
public void createCode() {
Random heightRandom = new Random();
int codeX = 0;
int fontHeight = 0;
fontHeight = height-heightRandom.nextInt(7)-7;// 字体的高度
codeX = width / (codeCount+1);// 每个字符的宽度
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体
ImgFontByte imgFont = new ImgFontByte();
Font font = imgFont.getFont(fontHeight);
g.setFont(font);
// 绘制干扰线
for (int i = 0; i < lineCount; i++) {
int xs = getRandomNumber(width);
int ys = getRandomNumber(height);
int xe = xs + getRandomNumber(width / 8);
int ye = ys + getRandomNumber(height / 8);
g.setColor(getRandomColor());
g.drawLine(xs, ys, xe, ye);
}
StringBuffer randomCode = new StringBuffer();
// int x = 5;
// 随机产生验证码字符
for (int i = 0; i < codeCount; i++) {
int h = height-8;
int w = (i + 1) * codeX+heightRandom.nextInt(4);
String strRand = String.valueOf(codeSequence[random
.nextInt(codeSequence.length)]);
// 设置字体颜色
g.setColor(getRandomColor());
int degree = new Random().nextInt() % 10;
g.rotate(degree * Math.PI / 180,(w+codeX-5)/2, (h+fontHeight)/2);
// 设置字体位置
g.drawString(strRand, w, h ); //getRandomNumber(height / 2) + 25
g.rotate(-degree * Math.PI / 150, (w+codeX-5)/2, (h+fontHeight)/2);
randomCode.append(strRand);
}
code = randomCode.toString();
}
/** 获取随机颜色 */
private Color getRandomColor() {
int r = getRandomNumber(225);
int g = getRandomNumber(225);
int b = getRandomNumber(225);
return new Color(r, g, b);
}
/** 获取随机数 */
private int getRandomNumber(int number) {
return random.nextInt(number);
}
public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}
public void write(OutputStream sos) throws IOException {
// ImageIO.write(buffImg, "png", sos);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(buffImg);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code;
}
/** 字体样式类 */
class ImgFontByte {
public Font getFont(int fontHeight) {
return new Font("Arial", Font.PLAIN, fontHeight);
}
}
}
public void scaptcha(){
HttpServletResponse response = ServletActionContext.getResponse();
response.reset();
// 设置响应的类型格式为图片格式
response.setContentType("image/jpeg");
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
ValidateCode instance = new ValidateCode();
CookieUtil.setCookie(response, "scaptcha", instance.getCode().toUpperCase(), null, -1);
try {
instance.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
在使用ImageIO.write时,发现在Linux平台上,会出现异常:
javax.imageio.IIOException: Can't create output stream
检查tomcat的日志,终于真相大白:
javax.imageio.IIOException: Can't create output stream!
at javax.imageio.ImageIO.write(ImageIO.java:1521)
Caused by: javax.imageio.IIOException: Can't create cache file!
at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:395)
at javax.imageio.ImageIO.write(ImageIO.java:1519)
... 34 more
Caused by: java.io.IOException: 系统找不到指定的路径。
原来是ImageIO.write(image, "jpeg", response.getOutputStream());
查看日志,发现是由找不到文件引起
Java.nio.file.NoSuchFileException: xxx.../temp/imageio4138671232726624650.tmp
在使用ImageIO进行图片写操作时,默认会使用缓存目录:${tomcat}/temp,在此缓存目录会生成缓存文件imageio4138671232726624650.tmp(这一串数字应该是当前时间戳,临时文件名),有些生产环境的tomcat,会将temp目录删除,因此报错
ImageIO.write(bi, "jpg", baos);
换成:
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(image);