package verificationCode;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
public class generateCode {
private static int width = 150;
private static int height = 48;
private static int codeCount = 4;
private static int xx = 25;
private static int fontHeight = 42;
private static int codeY = 42;
private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/**
* 生成一个map集合
* code为生成的验证码
* codePic为生成的验证码BufferedImage对象
* @return
*/
public static Map<String,Object> generateCodeAndPic() {
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics gd = buffImg.getGraphics();
Random random = new Random();
gd.setColor(Color.WHITE);
gd.fillRect(0, 0, width, height);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
gd.setFont(font);
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
gd.setFont(font);
int red = 0, green = 0, blue = 0;
StringBuffer randomCode = new StringBuffer();
for (int i = 0; i < codeCount; i++) {
String code = String.valueOf(codeSequence[random.nextInt(36)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
gd.setColor(new Color(red, green, blue));
gd.drawString(code, (i + 1) * xx, codeY);
randomCode.append(code);
}
for (int i = 0; i < 60; i++) {
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
gd.setColor(new Color(red, green, blue));
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(50);
int yl = random.nextInt(50);
gd.drawLine(x, y, x + xl, y + yl);
}
Map<String,Object> map =new HashMap<String,Object>();
map.put("code", randomCode);
map.put("codePic", buffImg);
return map;
}
public static void main(String[] args) throws Exception {
File file = new File("WebRoot/image/"+System.currentTimeMillis()+".jpg");
FileOutputStream out = null;
try {
if (!file.exists()) {
file.getParentFile().mkdir();
file.createNewFile();
}
out = new FileOutputStream(file);
Map<String,Object> map = generateCode.generateCodeAndPic();
ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", out);
System.out.println("验证码的值为:"+map.get("code"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}