輸出隨機圖片(CAPTCHA圖像):Completely Automated Public Turing Test to Tell Computers and Humans Apart (全自動區分計算機和人類的測試)
相關主要類(JDK 查看API)
BufferedImage:內存圖像
Graphics:畫筆
ImageIO:輸出圖像
放在html頁面上<img src/>
注意:瀏覽器默認會緩存圖片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
public static int WIDTH = 120 ; public static int HEIGHT = 25 ; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html" ); //創建內存圖像 BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); //勾勒圖像 Graphics graphics = image.getGraphics(); //設置背景 graphics.setColor(Color.WHITE); graphics.fillRect( 0 , 0 , WIDTH, HEIGHT); //設置邊框 graphics.setColor(Color.BLUE); graphics.drawRect( 1 , 1 , WIDTH- 2 , HEIGHT- 2 ); //畫干擾線 graphics.setColor(Color.YELLOW); for ( int i= 0 ;i< 8 ;i++){ int xStart = new Random().nextInt(WIDTH); int yStart = new Random().nextInt(HEIGHT); int xEnd = new Random().nextInt(WIDTH); int yEnd = new Random().nextInt(HEIGHT); graphics.drawLine(xStart, yStart, xEnd, yEnd); } //寫隨機數 graphics.setColor(Color.RED); int x = 5 ; for ( int i= 0 ;i< 4 ;i++){ graphics.drawString( new Random().nextInt( 9 )+ "" , x, 20 ); x+= 30 ; } response.setContentType( "image/jpeg" ); //設置響應格式 ImageIO.write(image, "jpeg" , response.getOutputStream()); } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/alex_zhuang/article/details/7249850