图片验证码(CAPTCHA,全称为Completely Automated Public Turing test to tell Computers and Humans Apart,即全自动区分计算机和人类的图灵测试)是一种用于区分用户是计算机还是人的公共全自动程序。它通常用于网站验证,以防止自动化程序(如垃圾邮件发送者或网络爬虫)滥用服务。
图片验证码通常包含一组随机生成的字符(数字、字母或两者结合),这些字符以扭曲、模糊或添加噪点的方式呈现,使得计算机难以通过图像识别技术自动读取,而人类用户则相对容易识别。
以下是一个简单的图片验证码生成示例,使用HTML5 Canvas绘制:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片验证码</title>
<style>
#captchaCanvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="captchaCanvas" width="120" height="40"></canvas>
<button onclick="generateCaptcha()">刷新验证码</button>
<script>
function generateCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 生成随机字符
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let captcha = '';
for (let i = 0; i < 5; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
// 绘制验证码
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#f5f5f5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#333';
ctx.fillText(captcha, 10, 28);
// 添加噪点
for (let i = 0; i < 100; i++) {
ctx.fillStyle = '#ccc';
ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 1, 1);
}
// 返回验证码值,实际应用中应存储在服务器端
console.log('验证码:', captcha);
}
generateCaptcha();
</script>
</body>
</html>
通过以上方法,可以实现一个基本的图片验证码系统,并根据实际需求进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云