PHP生成二維碼的兩個(gè)方法和實(shí)例_PHP
Jun 01, 2016 am 11:51 AM隨著科技的進(jìn)步,二維碼應(yīng)用領(lǐng)域越來越廣泛,本站之前已有文章介紹通過使用jQuery插件來生成二維碼,今天我給大家分享下如何使用PHP生成二維碼,以及如何生成中間帶LOGO圖像的二維碼。
利用Google API生成二維碼
Google提供了較為完善的二維碼生成接口,調(diào)用API接口很簡(jiǎn)單,以下是調(diào)用代碼:
復(fù)制代碼 代碼如下:
$urlToEncode="http://www.bitsCN.com";
generateQRfromGoogle($urlToEncode);
/**
?* google api 二維碼生成【QRcode可以存儲(chǔ)最多4296個(gè)字母數(shù)字類型的任意文本,具體可以查看二維碼數(shù)據(jù)格式】
?* @param string $chl 二維碼包含的信息,可以是數(shù)字、字符、二進(jìn)制信息、漢字。
?不能混合數(shù)據(jù)類型,數(shù)據(jù)必須經(jīng)過UTF-8 URL-encoded
?* @param int $widhtHeight 生成二維碼的尺寸設(shè)置
?* @param string $EC_level 可選糾錯(cuò)級(jí)別,QR碼支持四個(gè)等級(jí)糾錯(cuò),用來恢復(fù)丟失的、讀錯(cuò)的、模糊的、數(shù)據(jù)。
?*??????????????????????????? L-默認(rèn):可以識(shí)別已損失的7%的數(shù)據(jù)
?*??????????????????????????? M-可以識(shí)別已損失15%的數(shù)據(jù)
?*??????????????????????????? Q-可以識(shí)別已損失25%的數(shù)據(jù)
?*??????????????????????????? H-可以識(shí)別已損失30%的數(shù)據(jù)
?* @param int $margin 生成的二維碼離圖片邊框的距離
?*/
function generateQRfromGoogle($chl,$widhtHeight ='150',$EC_level='L',$margin='0')
{
??? $chl = urlencode($chl);
??? echo '
??? &cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl.'" alt="QR code" widhtHeight="'.$widhtHeight.'
??? " widhtHeight="'.$widhtHeight.'"/>';
}
使用PHP二維碼生成類庫(kù)PHP QR Code生成二維碼
PHP QR Code是一個(gè)PHP二維碼生成類庫(kù),利用它可以輕松生成二維碼,官網(wǎng)提供了下載和多個(gè)演示demo,查看地址:http://phpqrcode.sourceforge.net/。
下載官網(wǎng)提供的類庫(kù)后,只需要使用phpqrcode.php就可以生成二維碼了,當(dāng)然您的PHP環(huán)境必須開啟支持GD2。phpqrcode.php提供了一個(gè)關(guān)鍵的png()方法,其中參數(shù)$text表示生成二位的的信息文本;參數(shù)$outfile表示是否輸出二維碼圖片文件,默認(rèn)否;參數(shù)$level表示容錯(cuò)率,也就是有被覆蓋的區(qū)域還能識(shí)別,分別是L(QR_ECLEVEL_L,7%),M(QR_ECLEVEL_M,15%),Q(QR_ECLEVEL_Q,25%),H(QR_ECLEVEL_H,30%);參數(shù)$size表示生成圖片大小,默認(rèn)是3;參數(shù)$margin表示二維碼周圍邊框空白區(qū)域間距值;參數(shù)$saveandprint表示是否保存二維碼并顯示。
復(fù)制代碼 代碼如下:
public static function png($text, $outfile=false, $level=QR_ECLEVEL_L, $size=3, $margin=4,?
$saveandprint=false)?
{
??? $enc = QRencode::factory($level, $size, $margin);
??? return $enc->encodePNG($text, $outfile, $saveandprint=false);
}
調(diào)用PHP QR Code非常簡(jiǎn)單,如下代碼即可生成一張內(nèi)容為"http://www.bitsCN.com"的二維碼.
復(fù)制代碼 代碼如下:
include 'phpqrcode.php';
QRcode::png('http://www.bitsCN.com');
那么實(shí)際應(yīng)用中,我們會(huì)在二維碼的中間加上自己的LOGO,已增強(qiáng)宣傳效果。那如何生成含有l(wèi)ogo的二維碼呢?其實(shí)原理很簡(jiǎn)單,先使用PHP QR Code生成一張二維碼圖片,然后再利用php的image相關(guān)函數(shù),將事先準(zhǔn)備好的logo圖片加入到剛生成的原始二維碼圖片中間,然后重新生成一張新的二維碼圖片。
復(fù)制代碼 代碼如下:
include 'phpqrcode.php';?
$value = 'http://www.bitsCN.com'; //二維碼內(nèi)容
$errorCorrectionLevel = 'L';//容錯(cuò)級(jí)別
$matrixPointSize = 6;//生成圖片大小
//生成二維碼圖片
QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
$logo = 'logo.png';//準(zhǔn)備好的logo圖片
$QR = 'qrcode.png';//已經(jīng)生成的原始二維碼圖
?
if ($logo !== FALSE) {
??? $QR = imagecreatefromstring(file_get_contents($QR));
??? $logo = imagecreatefromstring(file_get_contents($logo));
??? $QR_width = imagesx($QR);//二維碼圖片寬度
??? $QR_height = imagesy($QR);//二維碼圖片高度
??? $logo_width = imagesx($logo);//logo圖片寬度
??? $logo_height = imagesy($logo);//logo圖片高度
??? $logo_qr_width = $QR_width / 5;
??? $scale = $logo_width/$logo_qr_width;
??? $logo_qr_height = $logo_height/$scale;
??? $from_width = ($QR_width - $logo_qr_width) / 2;
??? //重新組合圖片并調(diào)整大小
??? imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,?
??? $logo_qr_height, $logo_width, $logo_height);
}
//輸出圖片
imagepng($QR, 'helloweba.png');
echo '';
由于二維碼允許有一定的容錯(cuò)性,一般的二維碼即使在遮住部分但仍然能夠解碼,經(jīng)常我們掃描二維碼的時(shí)候掃描到甚至不到一半時(shí)就能解碼掃描結(jié)果,這是因?yàn)樯善鲿?huì)將部分信息重復(fù)表示來提高其容錯(cuò)度,這就是為什么我們?cè)诙S碼中間加個(gè)LOGO圖片并不影響解碼結(jié)果的原因。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Comments should explain "why" rather than "what was done", such as explaining business reasons rather than repeating code operations; 2. Add overview comments before complex logic, briefly explaining the process steps to help establish an overall impression; 3. Comments the "strange" code to explain the intention of unconventional writing, and avoid misunderstandings as bugs; 4. Comments are recommended to be concise, use // in single lines, use // in functions/classes/*.../ in order to maintain a unified style; 5. Avoid issues such as out of synchronization with the comments, too long comments or not deletion of the code, and ensure that the comments truly improve the readability and maintenance of the code.

This article answers several key questions for beginners to learn PHP. First, the method to quickly get started with basic syntax is to practice basic structures such as variables, conditional judgment and loops, such as using $ to define variables, echo output content, and if judgment conditions; second, the way to use PHP and HTML is to embed PHP code into HTML, wrap it, and pay attention to running in a server environment that supports PHP; third, the process of handling form submission and database connection includes: front-end submission of forms, PHP receives data, verifying data, using mysqli or PDO and other methods to connect to the database and perform insertion operations. At the same time, it is recommended to use ORM tools to improve security and convenience. The article emphasizes that learning PHP should focus on hands-on practice and gradually accumulate experience.

PHP string splicing uses dot operators, such as $a="Hello".$"World"; variables can be directly embedded in double quotes, such as echo "Hello,$name"; when splicing a large amount of content, it is recommended to initialize the empty string and append it, or use the array implode() to optimize performance; common errors include single quotes without parsing variables, missing punctuation marks, variables not assigned, etc. Note: 1. Dot numbers are used to concatenate any string 2. Double quotes support variable replacement but do not parse complex expressions 3. It is recommended to initialize first and then add gradually 4. Avoid mixing quotes causing variables to be unparsed.

When using if/else control structure for conditional judgment in PHP, the following points should be followed: 1. Use if/else when different code blocks need to be executed according to the conditions; 2. Execute if branches if the condition is true, enter else or elseif if they are false; 3. When multi-conditional judgment, elseif should be arranged in logical order, and the range should be placed in front of the front; 4. Avoid too deep nesting, it is recommended to consider switch or reconstruction above three layers; 5. Always use curly braces {} to improve readability; 6. Pay attention to Boolean conversion issues to prevent type misjudgment; 7. Use ternary operators to simplify the code in simple conditions; 8. Merge and repeat judgments to reduce redundancy; 9. Test boundary values to ensure the complete logic. Mastering these techniques can help improve code quality and stability.

Good comments can improve the readability of PHP code, the key is to explain "why" rather than "what to do". 1. Comments should explain the code intention, such as explaining the logic rather than repeating the code; 2. Add a brief description before complex logic to help quickly understand the purpose of the function; 3. Use comments to remind people of easy errors or special requirements, such as format or logic precautions; 4. Use TODO and FIXME to mark up to do or repair work to facilitate subsequent follow-up; 5. Keep comments and code updated synchronously to avoid misleading. Comments should be accurate, necessary and consistent in order to truly improve the readability of the code.

The first step is to clarify the goal, install the environment, write basic code, and learn to debug. First, determine what to do with PHP, then install the running environment with integrated tools, recommend XAMPP, Laragon or MAMP, and then write a simple PHP page to practice. Finally, master debugging methods such as opening error prompts, printing variables, and viewing logs, and gradually improve without rushing to achieve success.

There are two main ways to install PHP on Linux: use package manager to install and source code to compile and install. For newbies or users who do not have special requirements for the version, it is recommended to use a package manager to install it. For example, running sudoaptupdate and sudoaptinstallphp on Ubuntu/Debian. On CentOS, you can first install the EPEL source and then install it with yum. After the installation is completed, you can verify through php-v and install common extensions. If you need a specific version or custom function, you should choose source code compilation and installation. The specific steps include downloading the source code package, decompression, and configuration (such as ./configure--prefix=/usr/local/php--with-co

To quickly build a PHP environment, you can choose integrated tools such as XAMPP or MAMP, 1. Determine the environment selection: XAMPP and MAMP are suitable for beginners; 2. Install PHP: Download and decompress, configure environment variables and php.ini; 3. Use a web server: Apache is easier to use, and Nginx is suitable for high concurrency; 4. Debugging problems: Turn on error reports, check logs to check blank pages, database connection failures, or extension loading exceptions.
