在ASP.NET下實現數字和字元相混合的驗證碼
http://dev.csdn.net/develop/article/22/22618.shtm
首先,我要簡要說說Session和ViewState的用法,因為後面會用到它
把資料存放區在Session中:Session("key")="test"
從Session取值:dim testvalue as string=Session("key")
類似的:
把資料存放區在ViewState中:ViewState("key")="test"
從ViewState中取值:dim testvalue as string=ViewState("key")
關於ViewState的更詳細的資料,你可以參看MSDN的<<ASP.NET ViewState 初探>>一文
百聞不如一見,有時代碼本身就比任何解說更有表現力,所以在此就不對代碼解說太多了,本文實現的驗證碼需要用到兩個檔案:
gif.aspx 該檔案用於產生驗證碼
ValidateCode.aspx 該檔案用來測實驗證碼(即如何使用)
下面給出gif.aspx的完整代碼:
<%@ import namespace="System"%>
<%@ import namespace="System.io"%>
<%@ import namespace="System.Drawing"%>
<%@ import namespace="System.Drawing.Imaging"%>
<script language="vb" runat="server">
Sub Page_Load(Sender as object,e as eventargs)
'RndNum是一個自訂函數
dim VNum as string=RndNum(4)
Session("VNum")=VNum
ValidateCode(VNum)
End Sub
'產生圖象驗證碼函數
Sub ValidateCode(VNum)
Dim Img as System.Drawing.Bitmap
Dim g as Graphics
Dim ms as MemoryStream
dim gheight as integer=Int(Len(VNum)*11.5)
'gheight為圖片寬度,根據字元長度自動更改圖片寬度
img=new BitMap(Gheight,20)
g=Graphics.FromImage(img)
g.DrawString(VNum,(New Font("Arial",10)),(New SolidBrush(color.blue)),3,3)'在矩形內繪製字串(字串,字型,畫筆顏色,左上x.左上y)
ms=New MemoryStream()
img.Save(ms,ImageFormat.Png)
Response.ClearContent() '需要輸出圖象資訊 要修改HTTP頭
Response.ContentType="image/Png"
Response.BinaryWrite(ms.ToArray())
g.Dispose()
img.Dispose()
Response.End()
End Sub
'--------------------------------------------
'函數名稱:RndNum
'函數參數:VcodeNum--設定返回隨機字串的位元
'函數功能:產生數字和字元混合的隨機字串
Function RndNum(VcodeNum)
dim Vchar as string="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z"
dim VcArray() as string=split(Vchar,",") '將字串產生數組
dim VNum as string=""
dim i as byte
For i=1 to VcodeNum
Randomize
VNum=VNum & VcArray(Int(35*Rnd)) '數組一般從0開始讀取,所以這裡為35*Rnd
Next
Return VNum
End Function
</script>
那麼又應該如何使用該檔案產生的圖象驗證碼,看這句代碼:
<asp:Image id="Image1" runat="server" ImageUrl="gif.aspx" />
這就是用來顯示驗證碼的Image控制項,你可以把它放在任何你喜歡的地方,下面的給出詳細的使用代碼,你把它儲存為ValidateCode.aspx,並把它和gif.aspx放在同一目錄下,在瀏覽器中開啟ValidateCode.aspx,就可以測試它的效果了:
<script language="vb" Runat="Server">
Sub Page_Load(Sender as object,e as eventargs)
dim VNum as string=Session("VNum")
Session.Abandon()
ViewState("VNum")=VNum
End Sub
'下面的事件代碼是用來測實驗證碼,可以根據需要更改
Sub btnSubmit_click(sender as object,e as eventargs)
'判斷輸入的驗證碼與所給是否相同
If txtValidateCode.text=Cstr(ViewState("VNum")) then
lblShow.text="<font color='red'>提示:驗證通過</font>"
Else
lblShow.text="所填寫的驗證碼與所給的不符"
End If
End Sub
</script>
<html>
<body>
<form runat="server">
<div align="center">
<table width="750">
<!--DWLayoutTable-->
<tr>
<td width="256" height="46"> </td>
<td width="9"> </td>
<td width="88"> </td>
<td width="87"> </td>
<td width="100"> </td>
<td width="68"> </td>
<td width="97"> </td>
</tr>
<tr>
<td height="21"></td>
<td></td>
<td colspan="3" valign="top"><asp:label ID="lblShow" runat="server"></asp:label></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td height="14"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td height="21"> </td>
<td colspan="2" valign="middle">驗證碼:</td>
<td valign="top"><asp:Image id="Image1" runat="server" ImageUrl="gif.aspx" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td height="20"> </td>
<td colspan="2" valign="top">輸入驗證碼:</td>
<td valign="top"><asp:textbox ID="txtValidateCode" runat="server" TextMode="SingleLine" /></td>
<td colspan="2" valign="middle"><font color="#FF0000" size="2">*注意:區分大小寫</font></td>
<td> </td>
</tr>
<tr>
<td height="25"> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td height="19"> </td>
<td> </td>
<td> </td>
<td valign="top"><asp:button ID="btnSubmit" runat="server" Text="比較" onclick="btnSubmit_click" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
http://www.cnblogs.com/thcjp/archive/2006/07/06/444342.html
在使用ASP的時候,我們時常要藉助第三方控制項來實現一些圖象功能。而現在,ASP.NET的推出,我們已經沒有必要再使用第三方控制項來實現,因為ASP.NET 已經具有強大的功能來實現一些圖象處理。現在,我們就來看看怎樣使用ASP.NET的這一強大功能。
一、System.Drawing的使用
以下的舉例將示範在記憶體中產生一張圖片,然後,將這張圖片通過網頁顯示出來。需要瞭解的是,我們這裡輸出的不是HTML效果,而是實實在在的圖片(圖象),我們可以使用“另存新檔…”將輸出圖象儲存起來。
我們先來看看效果:
我們看到,這張圖片是一個漸層背景上有“看見了嗎”幾個字,當然,這個效果在PhotoShop等圖象處理軟體裡面很容易實現,但是,一些與資料庫結合的應用我們不可能將所有圖片都事先設計出來,這時候,利用ASP.NET來實現這些功能就顯得很重要了。我們來看原始碼:
<%@ page language="vb" contenttype="image/jpeg" %>
<%@ import namespace="system.drawing" %>
<%@ import namespace="system.drawing.imaging" %>
<%@ import namespace="system.drawing.drawing2d" %>
<%
'清空Response
response.clear
'建立一個120*30大小,24bit的BMP圖象;
dim imgOutput as New bitmap(120, 30, pixelformat.format24bpprgb)
'根據以上BMP建立一個新圖象;
dim g as graphics = graphics.fromimage(imgOutput)
g.clear(color.Green)
g.smoothingMode = smoothingMode.antiAlias
g.drawString("看見了嗎?", New font("黑體",16,fontstyle.bold),new SolidBrush(Color.White),New pointF(2,4))
g.FillRectangle(New linearGradientBrush(New point(0,0), New point(120,30), color.fromArgb(0,0,0,0),color.fromArgb(255,255,255,255)),0,0,120,30)
imgOutput.save(response.outputstream, imageformat.jpeg)
g.dispose()
imgOutput.dispose()
response.end
%>
在以上代碼中,我們看到和資料庫程式不同,這裡專門引入了圖象處理的名字空間system.drawing等。程式首先清空了Response,確保沒有輸出;然後,程式建立了一個120乘30大的BMP圖象,再在這個基礎上建立一個新圖象,建立圖象以後,我們首先“畫”出了字串“看見了嗎”,該字串為16大粗黑體,顏色為白色,位置為(2,4);最後,我們實現漸層效果。
以上舉例很簡單,但是如果和資料庫結合,我們可以實現很多使用ASP可能不敢想的效果。
二、讀取和改變圖象檔案大小
讀取圖片?直接使用HTML不就可以了?當然可以,我們這裡只是提供一種選擇和方法來實現這一功能,具體這一功能的使用,我們可能需要在實踐中更多的學習。先來看程式原始碼:
<% ' import all relevant namespaces %>
<%@ import namespace="System" %>
<%@ import namespace="System.Drawing" %>
<%@ import namespace="System.Drawing.Imaging" %>
<%@ import namespace="System.IO" %>
<script runat="server">
Sub sendFile()
dim g as System.Drawing.Image = System.Drawing.Image.FromFile(server.mappath(request("src")))
dim thisFormat=g.rawformat
dim imgOutput as New Bitmap(g, cint(request("width")), cint(request("height")))
if thisformat.equals(system.drawing.imaging.imageformat.Gif) then
response.contenttype="image/gif"
else
response.contenttype="image/jpeg"
end if
imgOutput.save(response.outputstream, thisformat)
g.dispose()
imgOutput.dispose()
end sub
Sub sendError()
dim imgOutput as New bitmap(120, 120, pixelformat.format24bpprgb)
dim g as graphics = graphics.fromimage(imgOutput)
g.clear(color.yellow)
g.drawString("錯誤!", New font("黑體",14,fontstyle.bold),systembrushes.windowtext, New pointF(2,2))
response.contenttype="image/gif"
imgOutput.save(response.outputstream, imageformat.gif)
g.dispose()
imgOutput.dispose()
end sub
</script>
<%
response.clear
if request("src")="" or request("height")="" or request("width")="" then
call sendError()
else
if file.exists(server.mappath(request("src"))) then
call sendFile()
else
call sendError()
end if
end if
response.end
%>
在以上的程式中,我們看到兩個函數,一個是SendFile,這一函數主要功能為顯示伺服器上的圖片,該圖片的大小通過Width和Height設定,同時,程式會自動檢測圖片類型;另外一個是SendError,這一函數的主要功能為伺服器上的圖片檔案不存在時,顯示錯誤資訊,這裡很有趣,錯誤資訊也是通過圖片給出的():
以上的程式顯示圖片並且改變圖片大小,現在,我們將這個程式進一步,顯示圖片並且保持圖片的長寬比例,這樣,和實際應用可能比較接近,特別是需要製作電子相簿或者是圖片網站的時候比較實用。我們先來看主要函數:
Function NewthumbSize(currentwidth, currentheight)
dim tempMultiplier as Double
if currentheight > currentwidth then
tempMultiplier = 200 / currentheight
Else
tempMultiplier = 200 / currentwidth
end if
dim NewSize as New Size(CInt(currentwidth * tempMultiplier), CInt(currentheight * tempMultiplier))
return NewSize
End Function
以上程式是增加的一個函數NewthumbSize,該函數專門處理改變一會的圖片大小,這個圖片的長寬和原圖片的長寬保持相同比例。其他部分請參考上文程式碼。
三、畫圖特效
如果只是將圖片顯示在網頁上,這樣未免顯得簡單。現在,我們來進一步感受ASP.NET的強大功能。我們將學習圖象處理中常用的圖象反轉、圖象切割、圖象展開等技巧。
先來看看程式效果:
仔細看,我們可以找到各種圖象處理效果。現在,我們來看看程式碼:
<%@ Page Language="vb" Debug="True" %>
<%@ import namespace="system.drawing" %>
<%@ import namespace="system.drawing.imaging" %>
<%@ import namespace="system.drawing.drawing2d" %>
<%
dim strFilename as string
dim i as System.Drawing.Image
strFilename = server.mappath("./chris-fsck.jpg")
i = System.Drawing.Image.FromFile(strFilename)
dim b as New system.drawing.bitmap(i.width, i.height, pixelformat.format24bpprgb)
dim g as graphics = graphics.fromimage(b)
g.clear(color.blue)
'旋轉圖片
i.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipX)
g.drawimage(i,New point(0,0))
i.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipY)
g.RotateTransform(10)
g.drawimage(i,New point(0,0))
g.RotateTransform(10)
g.drawimage(i,New point(20,20))
g.RotateTransform(10)
g.drawimage(i,New point(40,40))
g.RotateTransform(10)
g.drawimage(i,New point(40,40))
g.RotateTransform(-40)
g.RotateTransform(90)
g.drawimage(i,New rectangle(100,-400,100,50),New rectangle(20,20,i.width-20,i.height-20),GraphicsUnit.Pixel)
g.RotateTransform(-90)
' 展開圖片
g.drawimage(i,New rectangle(10,10,50,50),New rectangle(20,20,i.width-20,i.height-20),GraphicsUnit.Pixel)
g.drawimage(i,New rectangle(50,10,90,50),New rectangle(20,20,i.width-20,i.height-20),GraphicsUnit.Pixel)
g.drawimage(i,New rectangle(110,10,150,50),New rectangle(20,20,i.width-20,i.height-20),GraphicsUnit.Pixel)
'切割圖片
g.drawimage(i,50,100,New rectangle(180,80,60,110),GraphicsUnit.Pixel)
g.drawimage(i,140,100,New rectangle(180,80,60,110),GraphicsUnit.Pixel)
'旋轉圖片
i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX)
g.drawimage(i,230,100,New rectangle(180,110,60,110),GraphicsUnit.Pixel)
response.contenttype="image/jpeg"
b.save(response.outputstream, imageformat.jpeg)
b.dispose()
%>
在以上的程式中,我們看到實現圖象處理的各種技巧,仔細觀察,我們可以知道旋轉圖片其實是用了一個RotateFlip方法;而切割和展開圖片,完全是通過設定DrawImage的不同參數來實現。
四、總結
ASP.NET的圖象處理可以實現的功能很多,我們在這裡其實只是簡單的介紹,更多功能的應用,需要我們在實踐中摸索、總結。