這個包不經常用,需要手動導入,具體代碼如下:
public BufferedImage createCode(User user, long goodsId) {
if(user==null||goodsId<=0) {
return null;
}
int width=80;
int height=32;
//創建一個圖片
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
//設置背景顏色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
//畫邊框
g.setColor(Color.black);
g.drawRect(0, 0, width-1, height-1);
//創建一個隨機序列填充點
Random rdm=new Random();
//做50個干擾點
for (int i = 0; i < 50; i++) {
int x=rdm.nextInt(width);
int y=rdm.nextInt(height);
g.drawOval(x, y, 0, 0);
}
//填充隨機代碼
String verifyCode=appendCode(rdm);
g.setColor(new Color(0,100,0));
g.setFont(new Font("Candara",Font.BOLD,24));
g.drawString(verifyCode,8,24);
g.dispose();
int rnd=calc(verifyCode);
//加入redis將驗證碼
rs.set(MiaoShaKey.ver_code, user.getMobile()+","+goodsId, rnd);
return image;
}
/*-----------------------分割,補充上面生成Code的代碼------------------------------------------*/
//+ - *
private static char ops[]=new char[] {'+','-','*'};
private String appendCode(Random rdm) {
int num1=rdm.nextInt(10);
int num2=rdm.nextInt(10);
int num3=rdm.nextInt(10);
char op1=ops[rdm.nextInt(3)];
char op2=ops[rdm.nextInt(3)];
String exp=""+num1+op1+num2+op2+num3;
return exp;
}
/*-----------------------分割,利用引擎解決計算問題------------------------------------------*/
/*驗證圖形驗證碼 用到scriptEnige圖形引擎*/
@SuppressWarnings("restriction")
private int calc(String verifyCode) {
try {
ScriptEngineManager manager=new ScriptEngineManager();
ScriptEngine engine=manager.getEngineByName("javaScript");
return (Integer)engine.eval(verifyCode);
}catch(Exception E){
E.printStackTrace();
return 0;
}
}
}
完成之後,發佈驗證碼:
BufferedImage image=ms.createCode(user,goodsId);
try{
OutputStream out=response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
return Result.error(CodeMsg.SECKILL_ERROR);
}