<?php
require_once 'lib/phpqrcode.php';

class OthQrcode{
	/**
	 * @method    png
	 * @param     string     $url          [二维码地址]
	 * @param     boolean    $savePath     [保存路径]
	 * @param     integer    $level        [容错级别   1-3]
	 * @param     integer    $size         [生成二维码大小]
	 * @param     integer    $margin       [边框空白]
	 * @param     string     $logo         [添加的logo地址]
	 * @param     string     $logoSavePath [logo保存地址 不存默认覆盖]
	 * @return    [type]                   [返回  保存地址或 base64]
	 * @author lu
	 * @copyright 2019-01-04
	 */
	function png($url='',$savePath=false,$level=1,$size=4,$margin=2,$logo='',$logoSavePath=''){
		if(!empty($savePath)){
			//保存
			QRcode::png($url, $savePath, $level, $size, $margin);
			if(!empty($logo)&&file_exists($savePath)){
				$QR=file_get_contents($savePath);
				$logoSavePath=!empty($logoSavePath)?$logoSavePath:$savePath;
				return $this->addLogo($QR,$logo,$logoSavePath);
			}else{
				return $savePath;
			}
		}else{
			//不保存
			ob_start();
			QRcode::png($url, $savePath, $level, $size, $margin,false);
			$QR = ob_get_contents();
			$imageString=base64_encode($QR);
			ob_end_clean();
			$base64 = "data:image/png;base64,".$imageString;
			if(!empty($logo)){
				return $this->addLogo($QR,$logo,$logoSavePath);
			}else{
				return $base64;
			}
		}

	}
	private function addLogo($QR,$logo,$saveName=''){
		if (!empty($logo)) { 
			$QR = imagecreatefromstring($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; 

			//重新组合图片并调整大小 
			if(empty($saveName)){
				ob_start();
				imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height); 
				imagepng($QR);
				$base64= base64_encode(ob_get_contents());
				ob_end_clean();
				return "data:image/png;base64,".$base64;
			}else{
				imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height); 
				imagepng($QR, $saveName);
				return $saveName;
			}
		}
	}
}