/**
* 生成二维码
*
* @param text 二维码内容
*/
public static void zxingCodeCreate(String text, String filePath) throws Exception {
int width = 208; // 图像宽度
int height = 208; // 图像高度
String format = "png";//图片格式
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");//字符编码格式
hints.put(EncodeHintType.MARGIN, 0);//边框宽度
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
File file = new File(filePath);
if (!file.getParentFile().exists()) {//如果文件夹不存在,创建文件夹
file.mkdirs();
}
if (!file.exists()) {//如果文件不存在,创建文件
file.createNewFile();
}
ImageIO.write(image, format, file);
}
ImageIO的write方法提供了上面的3种重载形式,第2种方式是将图片写入服务器。1,3种可将图片输出到浏览器端;
相对上面生成二维码图片到本地(或服务器),以下是使用ImageIO生成图片验证码到浏览器的方法
/**
* 生成验证码
*
* @param response
*/
@RequestMapping("/valicode")
public void actionValicode(HttpServletResponse response) {
BufferedImage image = new BufferedImage(90, 30, BufferedImage.TYPE_INT_RGB);
String valicode = Valicode.drawImage(image);
String encryptString = BaseUtil.encrypt(valicode.toUpperCase(), BaseUtil.VALICODE_SALT);
Cookie cookie = new Cookie("vali", encryptString);
//cookie.setHttpOnly(true); //增强安全,避免一定程度的跨站攻击,tomcat7
cookie.setMaxAge(600);
cookie.setPath("/");
response.addCookie(cookie);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream output = null;
try {
output = response.getOutputStream();
ImageIO.write(image, "jpeg", output);
output.flush();
output.close();
} catch (IOException e) {
}
}