PHP中GD库的使用
1.基本步骤
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午9:34
* 熟悉步骤
*/
// 1.创建画布
$width = 500;
$height= 300;
$image=imagecreatetruecolor($width,$height);
// 2.创建颜色
$red=imagecolorallocate($image,255,0,0);
$blue=imagecolorallocate($image,0,0,255);
// 3.进行绘画
// 水平绘制字符
imagechar($image,5,50,100,'K',$red);
// 垂直绘制字符
imagecharup($image,4,100,100,'J',$blue);
// 水平绘制字符串
imagestring($image,4,200,100,"Hello",$blue);
// 4.输出或保存
header('content-type:image/jpeg');
imagejpeg($image);
//if(imagejpeg($image,'./1.jpg')) {
// echo '保存成功';
//} else {
// echo '保存失败';
//}
// 5.销毁画布
imagedestroy($image);
2.优化字体和画布
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午9:51
* 解决画布黑底,字体太丑问题
*/
// 创建画布
$image=imagecreatetruecolor(500,500);
// 创建颜色
$white=imagecolorallocate($image,255,255,255);
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
// 绘制填充矩形
imagefilledrectangle($image,0,0,500,500,$white);
// 采用自定义字体绘画
imagettftext($image,18,0,100,100,$randColor,'../ttf/Rekha.ttf',"Hello world!");
imagettftext($image,22,30,100,200,$randColor,'../ttf/msyh.ttf',"Hello world!");
// 展示
header('content-type:image/jpeg');
imagejpeg($image);
// 销毁
imagedestroy($image);
3.创建简单的验证码
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午10:38
* 实现验证码功能
*/
// 创建画布
$width=140;
$height=50;
$image=imagecreatetruecolor($width,$height);
// 创建颜色
$white=imagecolorallocate($image,255,255,255);
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
// 绘制填充矩形
imagefilledrectangle($image,0,0,$width,$height,$white);
// 开始绘制
$size=mt_rand(20,28);
$angle=mt_rand(-10,10);
$x=30;
$y=35;
$fontfile="../ttf/msyh.ttf";
$string=mt_rand(1000,9999);
imagettftext($image,$size,$angle,$x,$y,$randColor,$fontfile,$string);
// 展示
header('content-type:image/jpeg');
imagejpeg($image);
// 销毁
imagedestroy($image);
4.创建复杂的验证码
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午10:49
*/
// 随机颜色
function getRandColor($image) {
return imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
}
// 创建画布
$width=140;
$height=50;
$image=imagecreatetruecolor($width,$height);
// 创建颜色
$white=imagecolorallocate($image,255,255,255);
// 绘制填充矩形
imagefilledrectangle($image,0,0,$width,$height,$white);
// 开始绘制
$string = join('',array_merge(range(0,9),range('a','z'),range('A','Z')));
$length=4;
for($i=0;$i<$length;$i++) {
$size=mt_rand(20,28);
$textWidth = imagefontwidth($size);
$textHeight= imagefontheight($size);
$angle=mt_rand(-10,10);
// $x=20+30*$i;
// $y=35;
$x=($width/$length)*$i+$textWidth;
$y=mt_rand($height/2,$height-$textHeight);
$fontfile="../ttf/msyh.ttf";
$text = str_shuffle($string)[0];// 打乱之后取其一
imagettftext($image,$size,$angle,$x,$y,getRandColor($image),$fontfile,$text);
}
// 添加干扰元素
for($i=1;$i<=50;$i++) {
imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),getRandColor($image));
}
// 绘制线段
for ($i=1;$i<=3;$i++) {
imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$height),mt_rand(0,$width),getRandColor($image));
}
// 展示
header('content-type:image/jpeg');
imagejpeg($image);
// 销毁
imagedestroy($image);
5.封装验证码成函数
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午11:23
* 封装验证码成函数
*/
function getVerify($type,$length) {
// 随机颜色
function getRandColor($image) {
return imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
}
// 创建画布
$width=20+$length*40;
$height=50;
$image=imagecreatetruecolor($width,$height);
// 创建颜色
$white=imagecolorallocate($image,255,255,255);
// 绘制填充矩形
imagefilledrectangle($image,0,0,$width,$height,$white);
/**
* 默认是4
* 1-数字
* 2-字母
* 3-数字+字母
* 4-汉字
*/
$type=$type?$type:1;
$length=$length?$length:4;
switch ($type) {
case 1:
// 数字
$string = join('',array_rand(range(0,9),$length));
break;
case 2:
// 字母
$string = join('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'))),$length));
break;
case 3:
// 数字+字母
$string = join('',array_rand(array_flip(array_merge(range(0,9),range('a','z'),range('A','Z'))),$length));
break;
case 4:
// 汉字
$str="汤,科,技,积,极,拓,展,人,工,智,能,领,域,尤,其,在,深,度,学,习,和,视,觉,计,算,方,面,其,科,研,能,力,让,人,印,象,深,刻,阿,里,巴,巴,在,人,工,智,能,领,域,的,投,入,已,为,旗,下,业,务,带,来,显,著,效,益,今,后,我,们,将,继,续,在,人,工,智,能,领,域,作,出,投,资,我,们,期,待,与,商,汤,科,技,的,战,略,合,作,能,够,激,发,更,多,创,新,为,社,会,创,造,价,值";
$arr=explode(",",$str);
$string = join('',array_rand(array_flip($arr),$length));
break;
default:
exit('非法参数');
break;
}
for($i=0;$i<$length;$i++) {
$size=mt_rand(20,28);
$textWidth = imagefontwidth($size);
$textHeight= imagefontheight($size);
$angle=mt_rand(-10,10);
$x=($width/$length)*$i+$textWidth;
$y=mt_rand($height/2,$height-$textHeight);
$fontfile="../../ttf/msyh.ttf";
$text = mb_substr($string,$i,1,'UTF-8');
imagettftext($image,$size,$angle,$x,$y,getRandColor($image),$fontfile,$text);
}
// 添加干扰元素
for($i=1;$i<=50;$i++) {
imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),getRandColor($image));
}
// 绘制线段
for ($i=1;$i<=3;$i++) {
imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$height),mt_rand(0,$width),getRandColor($image));
}
// 展示
header('content-type:image/jpeg');
imagejpeg($image);
// 销毁
imagedestroy($image);
}
getVerify(3,6);
6.缩略图
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午11:22
* 图片处理
*/
$filename = "../images/iphone7.jpg";
$fileInfo = getimagesize($filename);
list($src_width,$src_height) = $fileInfo;
// 缩放
$dst_w = 100;
$dst_h = 100;
// 创建目标画布资源
$dst_image=imagecreatetruecolor($dst_w,$dst_h);
// 通过图片文件创建画布资源
$src_image=imagecreatefromjpeg($filename);
imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_width,$src_height);
imagejpeg($dst_image,'thumbs/thumb_100x100.jpg');
// 展示
header('content-type:image/jpeg');
imagejpeg($dst_image);
imagedestroy($dst_image);
7.等比例缩放
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午11:22
* 图片处理
*/
$filename = "../images/longmen.jpg";
if($fileInfo = getimagesize($filename)) {
list($src_w,$src_h) = $fileInfo;
} else {
exit('文件不是真实图片');
}
// 等比例缩放
// 设置最大宽和高
$dst_w = 300;
$dst_h = 600;
$ratio_orig = $src_w / $src_h;
if ($dst_w / $dst_h > $ratio_orig) {
$dst_w = $dst_h * $ratio_orig;
} else {
$dst_h = $dst_w / $ratio_orig;
}
// 创建目标画布资源
$dst_image=imagecreatetruecolor($dst_w,$dst_h);
// 通过图片文件创建画布资源
$src_image=imagecreatefromjpeg($filename);
imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
imagejpeg($dst_image,'../thumbs/thumb_same.jpg');
// 展示
header('content-type:image/jpeg');
imagejpeg($dst_image);
imagedestroy($dst_image);
imagedestroy($src_image);
优化处理
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-9
* Time: 上午11:22
* 图片处理
*/
$filename = "../images/longmen.jpg";
if($fileInfo = getimagesize($filename)) {
list($src_w,$src_h) = $fileInfo;
$mime = $fileInfo['mime'];
} else {
exit('文件不是真实图片');
}
// image/jpeg image/gif image/png
$createFun = str_replace('/','createfrom',$mime);
$outFun = str_replace('/','',$mime);
// 等比例缩放
// 设置最大宽和高
$dst_w = 300;
$dst_h = 600;
$ratio_orig = $src_w / $src_h;
if ($dst_w / $dst_h > $ratio_orig) {
$dst_w = $dst_h * $ratio_orig;
} else {
$dst_h = $dst_w / $ratio_orig;
}
// 创建目标画布资源
$dst_image=imagecreatetruecolor($dst_w,$dst_h);
// 通过图片文件创建画布资源
// $src_image=imagecreatefromjpeg($filename);
$src_image=$createFun($filename);
imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
// imagejpeg($dst_image,'../thumbs/thumb_same.jpg');
$outFun($dst_image,'../thumbs/thumb_same.jpg');
// 展示
header('content-type:image/jpeg');
//imagejpeg($dst_image);
$outFun($dst_image);
imagedestroy($dst_image);
imagedestroy($src_image);
8.文字水印
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-10
* Time: 上午10:56
* 加水印
*/
$filename = "../images/longmen.jpg";
$fileInfo = getimagesize($filename);
$mime = $fileInfo['mime'];
$createFun = str_replace('/','createfrom',$mime);
$outFun = str_replace('/',null,$mime);
$image = $createFun($filename);
//$red = imagecolorallocate($image,255,0,0);
$red = imagecolorallocatealpha($image,255,0,0,50); // 实现透明
$fontfile = "../ttf/msyh.ttf";
imagettftext($image,30,0,30,50,$red,$fontfile,"China你好");
header('content-type:'.$mime);
$outFun($image);
imagedestroy($image);
GD库综合使用
<?php
/**
* Created by PhpStorm.
* User: jiqing
* Date: 18-4-8
* Time: 上午11:58
*/
class SiemensAction extends CommonAction{
public function _initialize()
{
parent::_initialize();
header( "Access-Control-Allow-Origin:*" );
}
public function index(){
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if ($url == 'hotel.caomall.net/index.php/Siemens'){
header('Location:http://hotel.caomall.net/index.php/Siemens/');
return false;
}
$this->assign('$random_num',rand(1111,9999));
$this->display();
}
public function get_compose_pic() {
vendor('Func.Json');
$json = new Json();
file_put_contents("./log/jiqing_log.txt", "\n".json_encode($_POST), FILE_APPEND);
$logData = [];
$logData = $_POST;
// 创建画布
$bg_w = $_POST['bgWidth'];
$bg_h = $_POST['bgHeight'];
$dpi = $_POST['dpi'];
if ($dpi == 1) {
$bg_w *= 3;
$bg_h *= 3;
}
if ($dpi == 1.5) {
$bg_w *= 2;
$bg_h *= 2;
}
if ($dpi == 2) {
$bg_w *= 1.5;
$bg_h *= 1.5;
}
$img_w = $_POST['imgWidth'];
$img_h = $_POST['imgHeight'];
$percentRate = ($bg_w/1125);
$img_h = $img_h * (bcdiv($bg_w,$img_w,2));
$img_w = $bg_w;
if ($img_h > $bg_h) {
$true_h = $bg_h;
$true_h = $true_h - 30; // 防止太高
$true_w = $img_w;
} else {
$true_h = $img_h;
$true_w = $img_w;
}
$logData['true_h'] = $true_h;
$logData['true_w'] = $true_w;
$canvas_w = $true_w + 72;
$canvas_h = $true_h + 212;
$canvasImage = imagecreatetruecolor($canvas_w,$canvas_h);
// 创建颜色
$white=imagecolorallocate($canvasImage,255,255,255);
$green = imagecolorallocatealpha($canvasImage,103,159,27,20); // 实现透明
// 绘制填充矩形
imagefilledrectangle($canvasImage,0,0,$canvas_w,$canvas_h,$white);
// 添加固定文字
$fontsize1 = 44*$percentRate;
$text1 = "世界地球日 环保有创意";
$fontsize2 = 24*$percentRate;
$text2 = "长 按 二 维 码 定 制 你 的 环 保 创 意 海 报";
imagettftext($canvasImage,$fontsize1,0,36,$true_h + 36 + 80 ,$green,'/siemens/font/msyh.ttf',$text1);
imagettftext($canvasImage,$fontsize2,0,36,$true_h + 36 + 130 ,$green,'/siemens/font/msyh.ttf',$text2);
\PHPQRCode\QRcode::png("http://".$_SERVER['HTTP_HOST']."/index.php/Siemens/index", "./tmp/qrcode.png", 'L', 4, 2);
// 添加二维码
$qr_url = "http://".$_SERVER['SERVER_NAME']."/tmp/qrcode.png";
$qrImageZoomInfo = $this->_imageZoom($qr_url,true,150,150);
imagecopymerge($canvasImage,$qrImageZoomInfo['image'],$canvas_w - 186,$canvas_h - 170,0,0,$qrImageZoomInfo['width'],$qrImageZoomInfo['height'],80);
// 获取基础图片
$bgId = $_POST['bgId'];
$baseImageInfo = $this->_getBasePic($bgId);
// 固定缩放处理
$baseImage = $this->_imageZoomFixed($baseImageInfo['imgUrl'],true,$img_w,$img_h);
$baseImage = $baseImage['image'];
// 图片裁剪处理
$baseImage = $this->_imageCut($baseImage,$true_w,$true_h);
// 添加logo
$plugins = json_decode($_POST['plugins'],true)[0];
if ($plugins) {
// 有贴图
if ($plugins['type'] == 1) { // 贴图
$chartlet_w = $plugins['width'];
$chartlet_h = $plugins['height'];
$chartlet_top = $plugins['top'];
$chartlet_left= $plugins['left'];
if ($dpi == 1.5) {
$chartlet_w *= 2;
$chartlet_h *= 2;
$chartlet_top *= 2;
$chartlet_left *= 2;
}
if ($dpi == 2) {
$chartlet_w *= 1.5;
$chartlet_h *= 1.5;
$chartlet_top *= 1.5;
$chartlet_left *= 1.5;
}
if ($dpi == 1) {
$chartlet_w *= 3;
$chartlet_h *= 3;
$chartlet_top *= 3;
$chartlet_left *= 3;
}
$chartlet_url = "http://".$_SERVER['SERVER_NAME'].$plugins['src'];
$chartletImageZoomInfo = $this->_imageZoomFixed($chartlet_url,true,$chartlet_w,$chartlet_h);
imagecopymerge($baseImage,$chartletImageZoomInfo['image'],$chartlet_left,$chartlet_top,0,0,$chartlet_w,$chartlet_h,100);
} else { // 文字
$text_w = $plugins['width'];
$text_h = $plugins['height'];
$text_top = $plugins['top'];
$text_left= $plugins['left'];
if ($dpi == 1.5) {
$text_w *= 2;
$text_h *= 2;
$text_top *= 2;
$text_left *= 2;
}
if ($dpi == 2) {
$text_w *= 1.5;
$text_h *= 1.5;
$text_top *= 1.5;
$text_left *= 1.5;
}
if ($dpi == 1) {
$text_w *= 3;
$text_h *= 3;
$text_top *= 3;
$text_left *= 3;
}
$customText = $plugins['val'];
$customText = $this->_str_line($customText);
imagettftext($baseImage,44,0,$text_left,$text_top,$white,'/siemens/font/msyh.ttf',$customText);
}
}
// 增加logo
$logo_url = "http://".$_SERVER['SERVER_NAME']."/siemens/img/logo.png";
$logoImageInfo = $this->_imageZoom($logo_url,true,300);
imagecopymerge($baseImage,$logoImageInfo['image'],30,30,0,0,$logoImageInfo['width'],$logoImageInfo['height'],80);
// 合成到主画布
imagecopymerge($canvasImage,$baseImage,36,36,0,0,$true_w,$true_h,100);
$outImgPath = '/tmp/'.date('YmdHis').rand(1000,9999).'.jpg';
$flag = imagejpeg($canvasImage,".".$outImgPath);
// 日志
$logData['outImgPath'] = $outImgPath;
file_put_contents("./log/jiqing_log.txt", "\n".json_encode($logData), FILE_APPEND);
if($flag){
$json->setAttr('imgurl',$outImgPath);
$json->setErr(0,'图片合成成功');
$json->Send();
}else{
$json->setErr(10001,'图片合成失败');
$json->Send();
}
}
private function _str_line($str,$len = 10) {
function mb_str_split($str){
return preg_split('/(?<!^)(?!$)/u', $str );
}
$str_arr = mb_str_split($str);
$i = 0;
$new_str = "";
foreach($str_arr as $val) {
$new_str .= $val;
$i ++ ;
if ($i % 10 == 0) {
$new_str .= "\r\n";
}
}
return $new_str;
}
// 图片裁剪
private function _imageCut($source,$width,$height,$source_x = 0,$source_y = 0) {
// 创建画布
$copyimage=imagecreatetruecolor($width,$height);
// 创建颜色
$white=imagecolorallocate($copyimage,255,255,255);
imagefilledrectangle($copyimage,0,0,$width,$height,$white);
imagecopyresampled($copyimage,$source,0,0,$source_x,$source_y,$width,$height,$width,$height);
return $copyimage;
}
// 图片等比例缩放,背景透明处理
private function _imageZoom($filename,$is_transparent = true,$dst_w="200",$dst_h="200") {
if($fileInfo = getimagesize($filename)) {
list($src_w,$src_h) = $fileInfo;
$mime = $fileInfo['mime'];
} else {
exit('文件不是真实图片');
}
// image/jpeg image/gif image/png
$createFun = str_replace('/','createfrom',$mime);
$outFun = str_replace('/','',$mime);
// 等比例缩放
$ratio_orig = $src_w / $src_h;
if ($dst_w / $dst_h > $ratio_orig) {
$dst_w = $dst_h * $ratio_orig;
} else {
$dst_h = $dst_w / $ratio_orig;
}
// 创建目标画布资源
$dst_image=imagecreatetruecolor($dst_w,$dst_h);
// 透明处理
if ($is_transparent) {
$color=imagecolorallocate($dst_image,204,204,204);
imagecolortransparent($dst_image,$color);
imagefill($dst_image,0,0,$color);
}
// 通过图片文件创建画布资源
$src_image=$createFun($filename);
imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
$fileInfo['width'] = $dst_w;
$fileInfo['height'] = $dst_h;
$fileInfo['image'] = $dst_image;
imagedestroy($src_image);
// imagedestroy($dst_image);
return $fileInfo;
}
private function _imageZoomFixed($filename,$is_transparent = true,$dst_w="200",$dst_h="200") {
if($fileInfo = getimagesize($filename)) {
list($src_w,$src_h) = $fileInfo;
$mime = $fileInfo['mime'];
} else {
exit('文件不是真实图片');
}
// image/jpeg image/gif image/png
$createFun = str_replace('/','createfrom',$mime);
$outFun = str_replace('/','',$mime);
// 创建目标画布资源
$dst_image=imagecreatetruecolor($dst_w,$dst_h);
// 透明处理
if ($is_transparent) {
$color=imagecolorallocate($dst_image,153,153,153);
imagecolortransparent($dst_image,$color);
imagefill($dst_image,0,0,$color);
}
// 通过图片文件创建画布资源
$src_image=$createFun($filename);
imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
$fileInfo['width'] = $dst_w;
$fileInfo['height'] = $dst_h;
$fileInfo['image'] = $dst_image;
imagedestroy($src_image);
// imagedestroy($dst_image);
return $fileInfo;
}
// 获取基础图片信息
private function _getBasePic($media_id) {
// 获取accessToken
$access_token_url = C('WECHAT_PROXY_HOST') . 'AccessToken/get';
$access_res = Http::doGet($access_token_url);
$json = json_decode($access_res, true);
$accessToken = $json['data']['access_token'];
$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$accessToken."&media_id=".$media_id;
return $this->_getImageInfo($url);
}
// 获取图片信息
private function _getImageInfo($filename) {
if (@!$info = getimagesize($filename)) {
exit('文件不是真实图片');
}
$fileInfo['width'] = $info[0];
$fileInfo['height']= $info[1];
$mime = image_type_to_mime_type($info[2]);
$createFun = str_replace('/','createfrom',$mime);
$outFun = str_replace('/','',$mime);
$fileInfo['createFun'] = $createFun;
$fileInfo['outFun'] = $outFun;
$fileInfo['ext'] = strtolower(image_type_to_extension($info[2]));
$fileInfo['imgUrl'] = $filename;
return $fileInfo;
}
}