이 글에서는 주로 PHP에서 크기 설정, 로고 추가, 획, 둥근 모서리, 투명도 및 기타 처리를 지원하는 QR 코드 클래스를 만드는 방법을 소개합니다. 모든 사람이 쉽게 학습하고 사용할 수 있도록 완전한 코드, 데모 예제 및 자세한 매개변수 설명이 제공됩니다. 모두에게 도움이 되기를 바랍니다.
기능은 다음과 같습니다.
1. QR 코드 만들기
2. 로고를 획으로 그릴 수 있습니다.
4. 로고를 설정할 수 있습니다. 투명하게
6. 출력 이미지 유형은 png, jpg, gif 형식을 지원합니다.
7. 출력 이미지 품질을 설정할 수 있습니다.
설정 매개변수 설명:
QR 코드 품질 L-최소, M, Q, H-best
QR 코드 크기 1~50
생성된 QR 코드 이미지 경로
생성된 이미지 품질
로고 경로, 빈 수단 로고를 추가하지 않음
로고 크기, null은 QR 코드 크기에 비례하여 자동 계산됨을 의미
로고 획 크기, null은 로고 크기에 비례하여 자동 계산됨
로고 획 색상
로고 불투명도 0-100
로고 둥근 각도 0-30
코드는 다음과 같습니다.
PHPQR코드 .class.php<?phprequire_once dirname(__FILE__)."/qrcode/qrlib.php";/**
* PHP创建二维码类
* Date: 2018-03-18
* Author: fdipzone
* Version: 1.0
*
* Description:
* PHP实现创建二维码类,支持设置尺寸,加入LOGO,圆角,透明度,等处理。
*
* Func:
* public set_config 设定配置
* public generate 创建二维码
* private create_qrcode 创建纯二维码图片
* private add_logo 合拼纯二维码图片与logo图片
* private image_outline 图片对象进行描边
* private image_fillet 图片对象进行圆角处理
* private imagecopymerge_alpha 合拼图片并保留各自透明度
* private create_dirs 创建目录
* private hex2rgb hex颜色转rgb颜色
* private get_file_ext 获取图片类型
*/class PHPQRCode{ // class start
/** 默认设定 */
private $_config = array( 'ecc' => 'H', // 二维码质量 L-smallest, M, Q, H-best
'size' => 15, // 二维码尺寸 1-50
'dest_file' => 'qrcode.png', // 创建的二维码路径
'quality' => 100, // 图片质量
'logo' => '', // logo路径,为空表示没有logo
'logo_size' => null, // logo尺寸,null表示按二维码尺寸比例自动计算
'logo_outline_size' => null, // logo描边尺寸,null表示按logo尺寸按比例自动计算
'logo_outline_color' => '#FFFFFF', // logo描边颜色
'logo_opacity' => 100, // logo不透明度 0-100
'logo_radius' => 0, // logo圆角角度 0-30
); /**
* 设定配置
* @param Array $config 配置内容
*/
public function set_config($config){
// 允许设定的配置
$config_keys = array_keys($this->_config); // 获取传入的配置,写入设定
foreach($config_keys as $k=>$v){ if(isset($config[$v])){ $this->_config[$v] = $config[$v];
}
}
} /**
* 创建二维码
* @param String $data 二维码内容
* @return String
*/
public function generate($data){
// 创建临时二维码图片
$tmp_qrcode_file = $this->create_qrcode($data); // 合拼临时二维码图片与logo图片
$this->add_logo($tmp_qrcode_file); // 删除临时二维码图片
if($tmp_qrcode_file!='' && file_exists($tmp_qrcode_file)){
unlink($tmp_qrcode_file);
} return file_exists($this->_config['dest_file'])? $this->_config['dest_file'] : '';
} /**
* 创建临时二维码图片
* @param String $data 二维码内容
* @return String
*/
private function create_qrcode($data){
// 临时二维码图片
$tmp_qrcode_file = dirname(__FILE__).'/tmp_qrcode_'.time().mt_rand(100,999).'.png'; // 创建临时二维码
QRcode::png($data, $tmp_qrcode_file, $this->_config['ecc'], $this->_config['size'], 2); // 返回临时二维码路径
return file_exists($tmp_qrcode_file)? $tmp_qrcode_file : '';
} /**
* 合拼临时二维码图片与logo图片
* @param String $tmp_qrcode_file 临时二维码图片
*/
private function add_logo($tmp_qrcode_file){
// 创建目标文件夹
$this->create_dirs(dirname($this->_config['dest_file'])); // 获取目标图片的类型
$dest_ext = $this->get_file_ext($this->_config['dest_file']); // 需要加入logo
if(file_exists($this->_config['logo'])){ // 创建临时二维码图片对象
$tmp_qrcode_img = imagecreatefrompng($tmp_qrcode_file); // 获取临时二维码图片尺寸
list($qrcode_w, $qrcode_h, $qrcode_type) = getimagesize($tmp_qrcode_file); // 获取logo图片尺寸及类型
list($logo_w, $logo_h, $logo_type) = getimagesize($this->_config['logo']); // 创建logo图片对象
switch($logo_type){
case 1: $logo_img = imagecreatefromgif($this->_config['logo']); break;
case 2: $logo_img = imagecreatefromjpeg($this->_config['logo']); break;
case 3: $logo_img = imagecreatefrompng($this->_config['logo']); break;
default: return '';
} // 设定logo图片合拼尺寸,没有设定则按比例自动计算
$new_logo_w = isset($this->_config['logo_size'])? $this->_config['logo_size'] : (int)($qrcode_w/5); $new_logo_h = isset($this->_config['logo_size'])? $this->_config['logo_size'] : (int)($qrcode_h/5); // 按设定尺寸调整logo图片
$new_logo_img = imagecreatetruecolor($new_logo_w, $new_logo_h);
imagecopyresampled($new_logo_img, $logo_img, 0, 0, 0, 0, $new_logo_w, $new_logo_h, $logo_w, $logo_h); // 判断是否需要描边
if(!isset($this->_config['logo_outline_size']) || $this->_config['logo_outline_size']>0){ list($new_logo_img, $new_logo_w, $new_logo_h) = $this->image_outline($new_logo_img);
} // 判断是否需要圆角处理
if($this->_config['logo_radius']>0){ $new_logo_img = $this->image_fillet($new_logo_img);
} // 合拼logo与临时二维码
$pos_x = ($qrcode_w-$new_logo_w)/2; $pos_y = ($qrcode_h-$new_logo_h)/2;
imagealphablending($tmp_qrcode_img, true); // 合拼图片并保留各自透明度
$dest_img = $this->imagecopymerge_alpha($tmp_qrcode_img, $new_logo_img, $pos_x, $pos_y, 0, 0, $new_logo_w, $new_logo_h, $this->_config['logo_opacity']); // 生成图片
switch($dest_ext){ case 1: imagegif($dest_img, $this->_config['dest_file'], $this->_config['quality']); break; case 2: imagejpeg($dest_img, $this->_config['dest_file'], $this->_config['quality']); break; case 3: imagepng($dest_img, $this->_config['dest_file'], (int)(($this->_config['quality']-1)/10)); break;
}
// 不需要加入logo
}else{ $dest_img = imagecreatefrompng($tmp_qrcode_file); // 生成图片
switch($dest_ext){ case 1: imagegif($dest_img, $this->_config['dest_file'], $this->_config['quality']); break; case 2: imagejpeg($dest_img, $this->_config['dest_file'], $this->_config['quality']); break; case 3: imagepng($dest_img, $this->_config['dest_file'], (int)(($this->_config['quality']-1)/10)); break;
}
}
} /**
* 对图片对象进行描边
* @param Obj $img 图片对象
* @return Array
*/
private function image_outline($img){
// 获取图片宽高
$img_w = imagesx($img); $img_h = imagesy($img); // 计算描边尺寸,没有设定则按比例自动计算
$bg_w = isset($this->_config['logo_outline_size'])? intval($img_w + $this->_config['logo_outline_size']) : $img_w + (int)($img_w/5); $bg_h = isset($this->_config['logo_outline_size'])? intval($img_h + $this->_config['logo_outline_size']) : $img_h + (int)($img_h/5); // 创建底图对象
$bg_img = imagecreatetruecolor($bg_w, $bg_h); // 设置底图颜色
$rgb = $this->hex2rgb($this->_config['logo_outline_color']); $bgcolor = imagecolorallocate($bg_img, $rgb['r'], $rgb['g'], $rgb['b']); // 填充底图颜色
imagefill($bg_img, 0, 0, $bgcolor); // 合拼图片与底图,实现描边效果
imagecopy($bg_img, $img, (int)(($bg_w-$img_w)/2), (int)(($bg_h-$img_h)/2), 0, 0, $img_w, $img_h); $img = $bg_img; return array($img, $bg_w, $bg_h);
} /**
* 对图片对象进行圆角处理
* @param Obj $img 图片对象
* @return Obj
*/
private function image_fillet($img){
// 获取图片宽高
$img_w = imagesx($img); $img_h = imagesy($img); // 创建圆角图片对象
$new_img = imagecreatetruecolor($img_w, $img_h); // 保存透明通道
imagesavealpha($new_img, true); // 填充圆角图片
$bg = imagecolorallocatealpha($new_img, 255, 255, 255, 127);
imagefill($new_img, 0, 0, $bg); // 圆角半径
$r = $this->_config['logo_radius']; // 执行圆角处理
for($x=0; $x<$img_w; $x++){ for($y=0; $y<$img_h; $y++){ $rgb = imagecolorat($img, $x, $y); // 不在图片四角范围,直接画图
if(($x>=$r && $x<=($img_w-$r)) || ($y>=$r && $y<=($img_h-$r))){
imagesetpixel($new_img, $x, $y, $rgb); // 在图片四角范围,选择画图
}else{ // 上左
$ox = $r; // 圆心x坐标
$oy = $r; // 圆心y坐标
if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
imagesetpixel($new_img, $x, $y, $rgb);
} // 上右
$ox = $img_w-$r; // 圆心x坐标
$oy = $r; // 圆心y坐标
if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
imagesetpixel($new_img, $x, $y, $rgb);
} // 下左
$ox = $r; // 圆心x坐标
$oy = $img_h-$r; // 圆心y坐标
if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
imagesetpixel($new_img, $x, $y, $rgb);
} // 下右
$ox = $img_w-$r; // 圆心x坐标
$oy = $img_h-$r; // 圆心y坐标
if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
imagesetpixel($new_img, $x, $y, $rgb);
}
}
}
} return $new_img;
} // 合拼图片并保留各自透明度
private function imagecopymerge_alpha($dest_img, $src_img, $pos_x, $pos_y, $src_x, $src_y, $src_w, $src_h, $opacity){
$w = imagesx($src_img); $h = imagesy($src_img); $tmp_img = imagecreatetruecolor($src_w, $src_h);
imagecopy($tmp_img, $dest_img, 0, 0, $pos_x, $pos_y, $src_w, $src_h);
imagecopy($tmp_img, $src_img, 0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dest_img, $tmp_img, $pos_x, $pos_y, $src_x, $src_y, $src_w, $src_h, $opacity); return $dest_img;
} /**
* 创建目录
* @param String $path
* @return Boolean
*/
private function create_dirs($path){
if(!is_dir($path)){ return mkdir($path, 0777, true);
} return true;
} /** hex颜色转rgb颜色
* @param String $color hex颜色
* @return Array
*/
private function hex2rgb($hexcolor){
$color = str_replace('#', '', $hexcolor); if (strlen($color) > 3) { $rgb = array( 'r' => hexdec(substr($color, 0, 2)), 'g' => hexdec(substr($color, 2, 2)), 'b' => hexdec(substr($color, 4, 2))
);
} else { $r = substr($color, 0, 1) . substr($color, 0, 1); $g = substr($color, 1, 1) . substr($color, 1, 1); $b = substr($color, 2, 1) . substr($color, 2, 1); $rgb = array( 'r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b)
);
} return $rgb;
} /** 获取图片类型
* @param String $file 图片路径
* @return int
*/
private function get_file_ext($file){
$filename = basename($file); list($name, $ext)= explode('.', $filename); $ext_type = 0; switch(strtolower($ext)){ case 'jpg': case 'jpeg': $ext_type = 2; break; case 'gif': $ext_type = 1; break; case 'png': $ext_type = 3; break;
} return $ext_type;
}
} // class end?>
demo.php <?phprequire 'PHPQRCode.class.php';$config = array( 'ecc' => 'H', // L-smallest, M, Q, H-best
'size' => 12, // 1-50
'dest_file' => 'qrcode.png', 'quality' => 90, 'logo' => 'logo.jpg', 'logo_size' => 100, 'logo_outline_size' => 20, 'logo_outline_color' => '#FFFF00', 'logo_radius' => 15, 'logo_opacity' => 100,
);// 二维码内容$data = 'http://weibo.com/fdipzone';// 创建二维码类$oPHPQRCode = new PHPQRCode();// 设定配置$oPHPQRCode->set_config($config);// 创建二维码$qrcode = $oPHPQRCode->generate($data);// 显示二维码echo '<img src="/static/imghwm/default1.png" data-src="'.$qrcode.'?t='.time().'" class="lazy" alt="PHP는 로고가 있는 QR 코드 클래스를 구현합니다." >';?>
관련 권장 사항:
위 내용은 PHP는 로고가 있는 QR 코드 클래스를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP는 죽지 않고 끊임없이 적응하고 진화합니다. 1) PHP는 1994 년부터 새로운 기술 트렌드에 적응하기 위해 여러 버전 반복을 겪었습니다. 2) 현재 전자 상거래, 컨텐츠 관리 시스템 및 기타 분야에서 널리 사용됩니다. 3) PHP8은 성능과 현대화를 개선하기 위해 JIT 컴파일러 및 기타 기능을 소개합니다. 4) Opcache를 사용하고 PSR-12 표준을 따라 성능 및 코드 품질을 최적화하십시오.

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.

PHP에서, 특성은 방법 재사용이 필요하지만 상속에 적합하지 않은 상황에 적합합니다. 1) 특성은 클래스에서 다중 상속의 복잡성을 피할 수 있도록 수많은 방법을 허용합니다. 2) 특성을 사용할 때는 대안과 키워드를 통해 해결할 수있는 방법 충돌에주의를 기울여야합니다. 3) 성능을 최적화하고 코드 유지 보수성을 향상시키기 위해 특성을 과도하게 사용해야하며 단일 책임을 유지해야합니다.

의존성 주입 컨테이너 (DIC)는 PHP 프로젝트에 사용하기위한 객체 종속성을 관리하고 제공하는 도구입니다. DIC의 주요 이점에는 다음이 포함됩니다. 1. 디커플링, 구성 요소 독립적 인 코드는 유지 관리 및 테스트가 쉽습니다. 2. 유연성, 의존성을 교체 또는 수정하기 쉽습니다. 3. 테스트 가능성, 단위 테스트를 위해 모의 객체를 주입하기에 편리합니다.

SplfixedArray는 PHP의 고정 크기 배열로, 고성능 및 메모리 사용이 필요한 시나리오에 적합합니다. 1) 동적 조정으로 인한 오버 헤드를 피하기 위해 생성 할 때 크기를 지정해야합니다. 2) C 언어 배열을 기반으로 메모리 및 빠른 액세스 속도를 직접 작동합니다. 3) 대규모 데이터 처리 및 메모리에 민감한 환경에 적합하지만 크기가 고정되어 있으므로주의해서 사용해야합니다.

PHP는 $ \ _ 파일 변수를 통해 파일 업로드를 처리합니다. 보안을 보장하는 방법에는 다음이 포함됩니다. 1. 오류 확인 확인, 2. 파일 유형 및 크기 확인, 3 파일 덮어 쓰기 방지, 4. 파일을 영구 저장소 위치로 이동하십시오.

JavaScript에서는 NullCoalescingOperator (??) 및 NullCoalescingAssignmentOperator (?? =)를 사용할 수 있습니다. 1. 2. ??= 변수를 오른쪽 피연산자의 값에 할당하지만 변수가 무효 또는 정의되지 않은 경우에만. 이 연산자는 코드 로직을 단순화하고 가독성과 성능을 향상시킵니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

드림위버 CS6
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

뜨거운 주제



