<1>畫驗證碼核心類ValidateCodeAction
- package com.tarena.common.action;
-
- import java.awt.*;
- import java.awt.image.BufferedImage;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.util.Random;
- import javax.imageio.ImageIO;
- import javax.imageio.stream.ImageOutputStream;
- import com.opensymphony.xwork2.ActionContext;
- /**
- * 網頁中驗證碼的實現
- * @author JimmyZhang
- * @since 2012.5.10
- *
- */
- public class ValidateCodeAction {
-
- private ByteArrayInputStream inputStream;
- //默認的執行方法
- public String execute() throws Exception{
- Random r = new Random();
- //BufferedImage相當與緩存在內存中的圖像
- BufferedImage image =
- new BufferedImage(60,//繪圖區域的長度
- 20,//繪圖區域的高度
- BufferedImage.TYPE_INT_RGB);
- //獲取繪圖工具Graphiscs
- Graphics g = image.getGraphics();
- //設置繪圖顏色
- g.setColor(new Color(r.nextInt(255),
- r.nextInt(255),
- r.nextInt(255)));
- //從原點(0,0)填充繪圖區域
- g.fillRect(0, 0, 60, 20);
- //生成一個隨機的字符串(5位數字)
- String number = String.valueOf(r.nextInt(99999));
- //將number繪制在image中
- g.setColor(new Color(0,0,0));
- g.drawString(number, 5, 15);
- //將number保存在Session中
- ActionContext ac = ActionContext.getContext();
- ac.getSession().put("vcode", number);
- //畫干擾線
- for(int i=0; i<3;i++){
- drawLine(g,r);
- }
- //寫入到字節輸出流中
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- ImageOutputStream imageOutput =
- ImageIO.createImageOutputStream(output);
- //將圖像image寫入到imageOutput中
- ImageIO.write(image, "jpeg", imageOutput);
- //根據output構建inputStream
- inputStream = new ByteArrayInputStream(
- output.toByteArray());
- //對象之間的轉換--image-->ByteArrayOutStream-->ByteArrayInputStream
- return "success";
- }
-
- //輔助方法,用於繪制一條干擾線
- private void drawLine(Graphics g,Random r){
- g.setColor(new Color(r.nextInt(255),
- r.nextInt(255),
- r.nextInt(255)));
- //drawLine(x1,y1,x2,y2)
- g.drawLine(
- r.nextInt(60), r.nextInt(20),
- r.nextInt(60), r.nextInt(20));
- }
-
- public ByteArrayInputStream getInputStream() {
- return inputStream;
- }
-
- public void setInputStream(ByteArrayInputStream inputStream) {
- this.inputStream = inputStream;
- }
-
- }