jsp 驗證圖片
CODE 自己看註解囉,揪咪
http://www.hifreud.com/2015/05/11/random-code/
<%@page import="java.io.OutputStream"%>來源參考
<%@ page pageEncoding = "utf-8" contentType="image/jpeg"%>
<%@page import="java.awt.Font"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.util.Random"%>
<%@page import="java.awt.Color"%>
<%@page import="java.awt.Graphics"%>
<%@page import="java.awt.image.BufferedImage"%>
<%
//設定寬度
// final int WIDTH = 123;
final int WIDTH = 65;
//設定高度
final int HEIGHT = 20;
//設定亂數長度
final int LENGTH = 4;
//亂數內容-數字版
char[] ch = "0123456789".toCharArray();
//亂數內容-注音版
// char[] ch = "ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖ一ㄨㄩㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦ".toCharArray();
//亂數內容-五十音版
// char[] ch = "あかさたなはまやらわいきしちにひみりうくすつぬふむゆるんえけせてねへめれおこそとのほもよろを".toCharArray();
//建立圖片
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
Color color = new Color(200, 200, 200);
//設定底色
g.setColor(color);
g.fillRect(0, 0, WIDTH, HEIGHT);
Random r = new Random();
int len = ch.length, index;
//依據長度設置亂數
StringBuffer sb = new StringBuffer();
for (int i = 0; i < LENGTH; i++) {
index = r.nextInt(len);
sb.append(ch[index]);
//設定字體
g.setFont(new Font("Microsoft JhengHei", Font.CENTER_BASELINE, 20));
//設定固定顏色
g.setColor(Color.BLACK);
//亂數顏色調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
g.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110)));
g.drawString(ch[index] + "", (i * 15) + 3, 18);
}
//記錄Session備用
session.setAttribute("random", sb.toString());
// System.out.print(sb.toString());
//設定表頭
response.setDateHeader(
"Expires", 1L);
response.setHeader(
"Cache-Control", "no-cache, no-store, max-age=0");
response.addHeader(
"Pragma", "no-cache");
response.setContentType(
"image/jpeg");
//輸出圖片
OutputStream os = response.getOutputStream();
ImageIO.write(bi,
"jpg", os);
out.clear();
out = pageContext.pushBody();
%>
http://www.hifreud.com/2015/05/11/random-code/
網誌管理員已經移除這則留言。
回覆刪除