我正在尝试在我的网站上生成二维码。他们所要做的就是在其中包含一个 URL,我网站上的一个变量将提供该 URL。最简单的方法是什么?
7 回答
值得补充的是,除了@abaumg发布的二维码库外,谷歌还提供了一个二维码 API QR 码 API非常感谢@Toukakoukan的链接更新。
要使用这个,基本上:
https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8
300x300
是您要生成的 QR 图像的大小,- 是
chl
您要更改为 QR 码的 url 编码字符串,并且 - 这
choe
是(可选)编码。
上面的链接提供了更多详细信息,但要使用它,只需将src
图像指向操纵值,如下所示:
<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8" title="Link to Google.com" />
演示:
使用 PHP 生成 QR 码的最简单方法是phpqrcode 库。
phpqrcode 库的配置速度非常快,API 文档也很容易理解。
除了 abaumg 的回答之外,我还附上了PHP
来自http://phpqrcode.sourceforge.net/examples/index.php的 2 个示例
1.二维码编码器
首先包含本地路径中的库
include('../qrlib.php');
然后将图像直接输出为PNG流,例如:
QRcode::png('your texte here...');
将结果在本地保存为 PNG 图像:
$tempDir = EXAMPLE_TMP_SERVERPATH;
$codeContents = 'your message here...';
$fileName = 'qrcode_name.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = EXAMPLE_TMP_URLRELPATH.$fileName;
QRcode::png($codeContents, $pngAbsoluteFilePath);
2.二维码解码器
另见zxing解码器:
http://zxing.org/w/decode.jspx
检查输出非常有用。
3. 数据格式列表
根据数据类型,您可以在 QR 码中使用的数据格式列表:
- 网址:http ://stackoverflow.com (包括协议
http://
) - 电子邮件地址:mailto:name@example.com
- 电话号码:+16365553344(含国家代码)
- 短信:smsto:number:message
- 彩信:彩信:号码:主题
- YouTube 视频:youtube://ID(可在 iPhone 上使用,未标准化)
endroid /QrCode 库易于使用,维护良好,可以使用 composer 安装。还有一个捆绑包可以直接与 Symfony 一起使用。
安装:
$ composer require endroid/qrcode
用法 :
<?php
use Endroid\QrCode\QrCode;
$qrCode = new QrCode();
$qrCode
->setText('Life is too short to be generating QR codes')
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
->setLabel('Scan the code')
->setLabelFontSize(16)
->setImageType(QrCode::IMAGE_TYPE_PNG)
;
// now we can directly output the qrcode
header('Content-Type: '.$qrCode->getContentType());
$qrCode->render();
// or create a response object
$response = new Response($qrCode->get(), 200, array('Content-Type' => $qrCode->getContentType()));
我一直在使用google qrcode api,但我不太喜欢这个,因为它需要我在互联网上才能访问生成的图像。
我做了一点命令行研究,发现 linux 有一个qrencode
用于生成二维码的命令行工具。
我写了这个小脚本。好的部分是生成的图像大小小于 1KB。那么提供的数据只是一个网址。
$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));
$imgData = "data:image/png;base64,".base64_encode($img);
然后在 html 中加载图像:
<img class="emrQRCode" src="<?=$imgData ?>" />
你只需要安装它。[Linux 上的大多数成像应用程序都会在您没有意识到的情况下将其安装在后台。
我知道问题是如何使用 PHP 生成 QR 码,但对于正在寻找一种方法为网站生成代码的其他人来说,用纯 JavaScript 执行此操作是一个很好的方法。jquery-qrcode jquery 插件做得很好。