head.fix (BMP 檔頭 54 bytes) + body.fix (10 個數字 0-9 的 10x100 像素圖像資料,每數字 320 bytes)/captcha/ ├── code.asp # 主程式 ├── head.fix # BMP 檔頭 (54 bytes) ├── body.fix # 10 數字垂直排列圖像資料 (3200 bytes) └── demo.asp # 測試頁
<%@ Language=VBScript CodePage=65001 %>
<%
Option Explicit
Response.Buffer = True
Response.Expires = -1
Response.AddHeader "Pragma", "no-cache"
Response.AddHeader "Cache-Control", "no-cache, must-revalidate"
Response.ContentType = "image/bmp"
Dim zNum, i, j, zImg(3), nStr, pos
Dim adoSrc, adoDst
' 1. 產生 4 位隨機數 (1000-9999)
Randomize Timer
zNum = CInt(8999 * Rnd + 1000)
Session("CaptchaCode") = CStr(zNum) ' 驗證時比對
' 2. 拆解為陣列
nStr = CStr(zNum)
For i = 0 To 3
zImg(i) = CInt(Mid(nStr, i+1, 1))
Next
' 3. 開啟二進位串流
Set adoSrc = Server.CreateObject("ADODB.Stream")
adoSrc.Type = 1: adoSrc.Mode = 3: adoSrc.Open
Set adoDst = Server.CreateObject("ADODB.Stream")
adoDst.Type = 1: adoDst.Mode = 3: adoDst.Open
' 4. 載入 body.fix (10 數字 x 320 bytes = 3200 bytes)
adoSrc.LoadFromFile Server.MapPath("body.fix")
' 先寫入前 4 個數字佔位 (1280 bytes),稍後覆寫
adoDst.Write adoSrc.Read(1280)
' 5. 從來源提取 4 個隨機數字的像素區塊 (垂直條狀)
For i = 0 To 3
' 每數字 320 bytes,索引 9-zImg(i) 因圖像倒置存儲
adoSrc.Position = (9 - zImg(i)) * 320
adoDst.Position = i * 320
adoDst.Write adoSrc.Read(320)
Next
' 6. 載入檔頭
adoSrc.LoadFromFile Server.MapPath("head.fix")
pos = LenB(adoSrc.Read()) ' 54
adoSrc.Position = pos
adoDst.Position = pos
' 7. 將垂直條狀重組為橫向圖像 (轉置)
' 來源: 4 個 320-byte 區塊 (每區塊 10 行 x 32 bytes)
' 目標: 100 行 x 120 bytes (40像素 x 3bytes + 0 padding)
For i = 0 To 9 ' 10 行 (每數字高 10px)
For j = 0 To 3 ' 4 個數字
' 來源: 第 j 個數字的第 i 行 (30 bytes 像素 + 2 bytes padding = 32)
adoSrc.Position = j * 320 + i * 32
' 目標: 第 i 行的第 j 個數字區段
adoDst.Position = pos + i * 120 + j * 30
adoDst.Write adoSrc.Read(30) ' 只寫 30 bytes 像素 (無行尾 padding)
Next
Next
' 8. 輸出
adoDst.Position = 0
Response.BinaryWrite adoDst.Read()
' 清理
adoSrc.Close: Set adoSrc = Nothing
adoDst.Close: Set adoDst = Nothing
%>
用任何圖片編輯器 (Paint.NET、Photoshop) 建立:
或用 Python 腳本程式化產生:
# gen_captcha_assets.py
from PIL import Image, ImageDraw, ImageFont
import struct
# 建立 head.fix (40x100 BMP header)
img = Image.new('RGB', (40, 100), 'white')
bmp_header = b'BM' + struct.pack('
<%
Dim inputCode
inputCode = Trim(Request("captcha"))
If StrComp(inputCode, Session("CaptchaCode"), vbTextCompare) = 0 Then
Response.Write "驗證通過"
Else
Response.Write "驗證碼錯誤"
End If
%>
<img src="code.asp" id="captchaImg" style="vertical-align:middle;cursor:pointer"
onclick="this.src='code.asp?'+Math.random()" title="點擊更換">
<input name="captcha" maxlength="4" size="5">
GenerateCaptcha(width, height, length) 介面