在JSP頁面中動態生成圖片驗證碼的方法實例

今天小編就爲大家分享一篇關於在JSP頁面中動態生成圖片驗證碼的方法實例,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

在JSP頁面中動態生成圖片驗證碼

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page 
import="java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*" %>
<%@ taglib http://struts.apache.org/tags-bean">http://struts.apache.org/tags-bean" 
prefix="bean" %>
<%@ taglib http://struts.apache.org/tags-html">http://struts.apache.org/tags-html" 
prefix="html" %>
<%@ taglib http://struts.apache.org/tags-logic">http://struts.apache.org/tags-logic" 
prefix="logic" %>
<%@ taglib http://struts.apache.org/tags-tiles">http://struts.apache.org/tags-tiles" 
prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
 <head>
  <html:base />
  <title>MyJsp.jsp</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">  
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
-->
 </head>
 <body>
<h3>在jsp頁面生成驗證碼</h3>
<hr/>
<%
 //out.clear();
 //response.setContentType("image/jpeg");//設置響應類型
 //response.addHeader("pragma","NO-cache");
 //response.addHeader("Cache-Control","no-cache");
 //response.addDateHeader("Expries",0);
 int width=400, height=30;//圖片的大小(寬和高)
 //構架畫布,第一個參數表示畫布的寬,第二個參數表示畫布的高,第三個參數的含義有待確定
 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 Graphics g = image.getGraphics();//實例化畫圖對象
 //以下設置背景色
 g.setColor(Color.yellow); 
 Font DeFont=new Font("宋體", Font.ITALIC, 20);
 g.setFont(DeFont);
 //將已經設置好的背景顏色填充到指定的畫布區域
 g.fillRect(0,0, width, height);
 //置字體色
 g.setColor(Color.blue);
 int x=10,y=10,xl=550,yl=15;
 g.drawLine(x,y,x+xl,y+yl); 
 //在畫布中畫橢圓形,參數爲橢圓的座標,用於確定橢圓的大小
 g.drawOval(0,10,200,10);
 //在畫布上輸出文字信息,第一個參數表示要顯示的文字,第二和第三個參數表示起始點的X、Y座標
 g.drawString("想要輸出的文字-我是陳杉",70,20);
 g.dispose();
 ServletOutputStream outStream = response.getOutputStream();
 JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(outStream);
 encoder.encode(image);
 outStream.close();
%>
 </body>
</html:html>

--將該文件保存爲pic.jsp,該文件負責生成圖片!如果要在其他的頁面顯示該圖片只需要寫上

<img src="pic.jsp"/>

僅此一句就ok了,適用於生成各種驗證碼!

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章