Beginner 8分钟 3 steps
二维码生成API使用教程
快速集成二维码生成功能到你的应用,支持自定义尺寸、颜色和格式。
#二维码
#QR Code
#图像生成
#工具API
Prerequisites
- 了解 URL 编码基础知识
- HTML/CSS 基础
Overview
什么是二维码API?
二维码(QR Code)是一种可以存储大量信息的矩阵条码。通过二维码API,开发者可以动态生成二维码图片,用于:
- 网址分享:快速分享链接
- 支付收款:支付宝、微信支付收款码
- 会员卡:电子会员卡二维码
- 信息传递:名片、产品溯源
- 登录验证:扫码登录
Step-by-Step Guide
1
第一步:了解二维码生成API
使用 QR Server API 生成二维码,支持多种自定义选项。
bash
# 基础格式
https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Hello
# 常用参数
# size: 图片尺寸 (最大 1000x1000)
# data: 要编码的内容 (URL编码)
# margin: 白色边距
# color: 前景色 (RRGGBB)
# bgcolor: 背景色 (RRGGBB)
# 示例:生成 300x300 的蓝色二维码
https://api.qrserver.com/v1/create-qr-code/?size=300x300&color=0000FF&data=https://example.com
# 示例:编码中文内容
https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=%E4%BD%A0%E5%A5%BD
Tips
- data 参数需要进行 URL 编码
- 尺寸建议 200x200 到 500x500 之间
- 前景色和背景色使用十六进制 RGB 格式
2
第二步:在网页中显示二维码
使用 img 标签直接显示二维码图片。
html
<!DOCTYPE html>
<html>
<head>
<title>二维码生成器</title>
</head>
<body>
<h1>二维码生成器</h1>
<div>
<label>输入内容:</label>
<input type="text" id="content" value="https://example.com" />
<button onclick="generateQR()">生成二维码</button>
</div>
<div id="qrcode">
<!-- 二维码将显示在这里 -->
<img id="qr-img" src="" alt="二维码" />
</div>
<script>
function generateQR() {
const content = document.getElementById('content').value;
const encoded = encodeURIComponent(content);
const size = '300x300';
const url = `https://api.qrserver.com/v1/create-qr-code/?size=${size}&data=${encoded}`;
document.getElementById('qr-img').src = url;
}
// 页面加载时自动生成
generateQR();
</script>
</body>
</html>
Tips
- 使用 encodeURIComponent 处理特殊字符
- 二维码可以直接设置为 img 标签的 src
- 图片会实时生成,无需后端存储
3
第三步:JavaScript 动态生成
使用 JavaScript 动态生成和下载二维码。
javascript
// 动态生成二维码
function createQRCode(content, options = {}) {
const {
size = 300,
color = '000000',
bgcolor = 'ffffff'
} = options;
const encoded = encodeURIComponent(content);
return `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&color=${color}&bgcolor=${bgcolor}&data=${encoded}`;
}
// 生成带样式的二维码
const qrUrl = createQRCode('https://example.com', {
size: 500,
color: '0066cc', // 蓝色
bgcolor: 'f0f8ff' // 浅蓝背景
});
// 显示二维码
const img = document.createElement('img');
img.src = qrUrl;
document.body.appendChild(img);
// 下载二维码
function downloadQR(content) {
const url = createQRCode(content, { size: 500 });
const a = document.createElement('a');
a.href = url;
a.download = 'qrcode.png';
a.click();
}
downloadQR('https://example.com');
Tips
- 生成后可以直接右键保存图片
- 大尺寸二维码扫描成功率更高
- 对比度高的颜色组合效果更好
Common Errors & Solutions
二维码无法扫描
减小数据量或增加二维码尺寸。复杂内容建议使用短链接。
中文内容乱码
确保使用 encodeURIComponent 正确编码中文。
图片不显示
检查 URL 是否正确,某些特殊字符需要额外编码。