正在生成二维码...
填写左侧参数后点击生成
API 请求地址:
功能强大的二维码生成工具,支持多种自定义选项(下滑查看API文档)
正在生成二维码...
为开发者提供简单易用的二维码生成API
参数名 | 类型 | 必填 | 默认值 | 说明 |
---|---|---|---|---|
data |
string | 是 | - | 要生成二维码的内容(网址、文本等) |
size |
integer | 否 | 300 | 二维码大小(像素),支持 100-1000 |
color |
string | 否 | 000000 | 前景色,6位十六进制颜色代码(不含#) |
bgcolor |
string | 否 | ffffff | 背景色,6位十六进制颜色代码(不含#) |
ecc |
string | 否 | M | 容错级别:L(低)、M(中)、Q(高)、H(最高) |
margin |
integer | 否 | 1 | 内边距,支持 0-4 |
format |
string | 否 | png | 图片格式:png、jpg、gif、svg |
// 浏览器端 JavaScript
async function generateQRCode() {
const params = new URLSearchParams({
data: 'https://example.com',
size: '300',
color: '000000',
bgcolor: 'ffffff',
ecc: 'M',
margin: '1',
format: 'png'
});
try {
const response = await fetch(`/qrcode?${params.toString()}`);
if (!response.ok) {
throw new Error(await response.text());
}
const blob = await response.blob();
const imageUrl = URL.createObjectURL(blob);
// 显示图片
const img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img);
// 下载图片
const a = document.createElement('a');
a.href = imageUrl;
a.download = 'qrcode.png';
a.click();
} catch (error) {
console.error('生成二维码失败:', error);
}
}
// Node.js
const fs = require('fs');
const https = require('https');
const { URLSearchParams } = require('url');
function generateQRCode() {
const params = new URLSearchParams({
data: 'https://example.com',
size: '300',
color: '000000',
bgcolor: 'ffffff',
ecc: 'M',
margin: '1',
format: 'png'
});
const url = `https://yourdomain.com/qrcode?${params.toString()}`;
const file = fs.createWriteStream('qrcode.png');
https.get(url, (response) => {
if (response.statusCode === 200) {
response.pipe(file);
file.on('finish', () => {
file.close();
console.log('二维码保存成功: qrcode.png');
});
} else {
console.error('生成二维码失败:', response.statusCode);
}
}).on('error', (error) => {
console.error('请求失败:', error);
});
}
generateQRCode();
# Python
import requests
from urllib.parse import urlencode
def generate_qrcode():
params = {
'data': 'https://example.com',
'size': '300',
'color': '000000',
'bgcolor': 'ffffff',
'ecc': 'M',
'margin': '1',
'format': 'png'
}
url = f"https://yourdomain.com/qrcode?{urlencode(params)}"
try:
response = requests.get(url)
response.raise_for_status()
# 保存图片
with open('qrcode.png', 'wb') as f:
f.write(response.content)
print('二维码保存成功: qrcode.png')
except requests.exceptions.RequestException as e:
print(f'生成二维码失败: {e}')
# 使用示例
if __name__ == '__main__':
generate_qrcode()
<?php
// PHP cURL 二维码生成示例
/**
* 使用cURL生成二维码并保存到本地
* @param string $data 要生成二维码的内容
* @param array $options 可选参数
* @return bool 是否成功
*/
function generateQRCode($data, $options = []) {
// 默认参数
$defaultOptions = [
'size' => '300',
'color' => '000000',
'bgcolor' => 'ffffff',
'ecc' => 'M',
'margin' => '1',
'format' => 'png'
];
// 合并参数
$params = array_merge($defaultOptions, $options);
$params['data'] = $data;
// 构建API URL
$apiUrl = "https://yourdomain.com/qrcode?" . http_build_query($params);
// 初始化cURL
$ch = curl_init();
// 设置cURL选项
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true, // 返回响应内容而非直接输出
CURLOPT_TIMEOUT => 30, // 30秒超时
CURLOPT_CONNECTTIMEOUT => 10, // 10秒连接超时
CURLOPT_USERAGENT => 'PHP QR Code Generator 1.0',
CURLOPT_FOLLOWLOCATION => true, // 跟随重定向
CURLOPT_MAXREDIRS => 3, // 最多3次重定向
CURLOPT_SSL_VERIFYPEER => true, // 验证SSL证书
CURLOPT_SSL_VERIFYHOST => 2, // 验证主机名
CURLOPT_HTTPHEADER => [
'Accept: image/png,image/jpeg,image/gif,image/svg+xml,*/*',
'Cache-Control: no-cache'
]
]);
// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$error = curl_error($ch);
// 关闭cURL资源
curl_close($ch);
// 检查错误
if ($error) {
echo "❌ cURL 错误: {$error}\n";
return false;
}
if ($httpCode !== 200) {
echo "❌ HTTP 错误: {$httpCode}\n";
if ($response) {
echo "错误信息: " . substr($response, 0, 200) . "\n";
}
return false;
}
// 验证响应内容类型
if (!strpos($contentType, 'image/') && $params['format'] !== 'svg') {
echo "❌ 返回内容不是图片格式\n";
return false;
}
// 生成文件名
$timestamp = date('Y-m-d_H-i-s');
$filename = "qrcode_{$timestamp}.{$params['format']}";
// 保存文件
$result = file_put_contents($filename, $response);
if ($result === false) {
echo "❌ 保存文件失败\n";
return false;
}
// 成功信息
echo "✅ 二维码生成成功: {$filename}\n";
echo "📏 尺寸: {$params['size']}x{$params['size']}\n";
echo "🎨 格式: " . strtoupper($params['format']) . "\n";
echo "📁 大小: " . number_format($result) . " 字节\n";
return true;
}
// 基本用法示例
echo "=== 基本用法 ===\n";
generateQRCode('https://example.com');
echo "\n=== 自定义参数 ===\n";
generateQRCode('Hello, 世界! 🌍', [
'size' => '400',
'color' => 'FF0000', // 红色前景
'bgcolor' => 'FFFF00', // 黄色背景
'ecc' => 'H', // 最高容错级别
'margin' => '2', // 中等边距
'format' => 'svg' // SVG格式
]);
echo "\n=== 批量生成 ===\n";
$urls = [
'https://github.com',
'https://stackoverflow.com',
'https://php.net'
];
foreach ($urls as $index => $url) {
echo "生成第 " . ($index + 1) . " 个二维码...\n";
generateQRCode($url, [
'size' => '250',
'format' => 'png'
]);
}
echo "\n=== 错误处理示例 ===\n";
/**
* 带完整错误处理的生成函数
*/
function generateQRCodeSafe($data, $options = []) {
try {
// 验证输入
if (empty($data)) {
throw new Exception("数据不能为空");
}
if (strlen($data) > 4000) {
throw new Exception("数据长度不能超过4000字符");
}
$result = generateQRCode($data, $options);
if (!$result) {
throw new Exception("二维码生成失败");
}
return true;
} catch (Exception $e) {
echo "❌ 异常: " . $e->getMessage() . "\n";
return false;
}
}
// 安全生成示例
generateQRCodeSafe('测试安全生成', [
'size' => '300',
'color' => '0066CC',
'bgcolor' => 'F0F8FF'
]);
?>
// Go
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
)
func generateQRCode() error {
params := url.Values{}
params.Set("data", "https://example.com")
params.Set("size", "300")
params.Set("color", "000000")
params.Set("bgcolor", "ffffff")
params.Set("ecc", "M")
params.Set("margin", "1")
params.Set("format", "png")
apiURL := "https://yourdomain.com/qrcode?" + params.Encode()
resp, err := http.Get(apiURL)
if err != nil {
return fmt.Errorf("请求失败: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("生成二维码失败: %d", resp.StatusCode)
}
file, err := os.Create("qrcode.png")
if err != nil {
return fmt.Errorf("创建文件失败: %v", err)
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
return fmt.Errorf("保存文件失败: %v", err)
}
fmt.Println("二维码保存成功: qrcode.png")
return nil
}
func main() {
if err := generateQRCode(); err != nil {
fmt.Printf("错误: %v\n", err)
}
}
# cURL 命令行
# 基本用法
curl "https://yourdomain.com/qrcode?data=https://example.com" \
-o qrcode.png
# 带参数的完整示例
curl "https://yourdomain.com/qrcode?data=https://example.com&size=400&color=FF0000&bgcolor=FFFF00&ecc=H&margin=2&format=png" \
-o qrcode.png
# 生成SVG格式
curl "https://yourdomain.com/qrcode?data=Hello%20World&format=svg" \
-o qrcode.svg
# 使用变量
URL="https://example.com"
SIZE="500"
COLOR="000000"
BGCOLOR="ffffff"
curl "https://yourdomain.com/qrcode?data=${URL}&size=${SIZE}&color=${COLOR}&bgcolor=${BGCOLOR}" \
-o qrcode.png
echo "二维码已保存为 qrcode.png"