PHP生成一張含有二維碼的圖片(文章末尾附程式碼下載連結)
阿新 • • 發佈:2019-01-28
PHP生成一張圖片用到的類有QRcode,QRencode ,QRtools , QRimage這四個類是主要的。
主導類:QRcode
輔助類:QRencode, QRimage ,QRtools .
請看下圖, 直接貼原始碼!!!
1、直接呼叫函式(引數賦值,返回圖片);
//QRcode
public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
{
$enc = QRencode::factory($level , $size, $margin);
// var_dump($enc);
return $enc->encodePNG($text, $outfile, $saveandprint=false);
}
2、轉碼過程,進行工廠模式轉化;
//QRencode
public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4)
{
// echo "run Qrencode::factory....<br/>";
$enc = new QRencode();
$enc ->size = $size;
$enc->margin = $margin;
switch ($level.'') {
case '0':
case '1':
case '2':
case '3':
$enc->level = $level;
break;
case 'l':
case 'L':
$enc->level = QR_ECLEVEL_L;
break ;
case 'm':
case 'M':
$enc->level = QR_ECLEVEL_M;
break;
case 'q':
case 'Q':
$enc->level = QR_ECLEVEL_Q;
break;
case 'h':
case 'H':
$enc->level = QR_ECLEVEL_H;
break;
}
return $enc;
}
3、記錄過程資訊
//QRencode
public function encodePNG($intext, $outfile = false, $saveandprint=false)
{
// echo "run Qrencode::encodePNG....<br/>";
try {
ob_start();
$tab = $this->encode($intext);
$err = ob_get_contents(); //獲取物件內容
ob_end_clean(); //清除
if ($err != '')
QRtools::log($outfile, $err); //記錄錯誤
$maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));
// echo "run Qrencode::maxSize....".$maxSize."<br/>".QR_PNG_MAXIMUM_SIZE."<br/>";
QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);
} catch (Exception $e) {
//記錄資訊
QRtools::log($outfile, $e->getMessage());
}
}
4、生成二維碼
//QRencode
public function encode($intext, $outfile = false)
{
//echo "run Qrencode::encode....<br/>";
$code = new QRcode();
if($this->eightbit) {
$code->encodeString8bit($intext, $this->version, $this->level);
} else {
$code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
}
// QRtools::markTime('after_encode');
$binarized = QRtools::binarize($code->data);
if ($outfile!== false) {
file_put_contents($outfile, join("\n", $binarized));
}
return $binarized;
}
5、輸出圖片
//QRimage
public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)
{
$image = self::image($frame, $pixelPerPoint, $outerFrame);
if ($filename === false) {
Header("Content-type: image/png");
ImagePng($image);
} else {
if($saveandprint===TRUE){
ImagePng($image, $filename);
header("Content-type: image/png");
ImagePng($image);
}else{
ImagePng($image, $filename);
}
}
ImageDestroy($image);
}