public function generateWithFont($filename,$str){ //创建一张画布设置宽高 $img = imagecreate(430, 490); //导入子图绝对路径 putenv('GDFONTPATH=' . realpath('.')); //设置画布背景色 imagecolorallocate($img, 255, 255, 255); //字体颜色 $color = imagecolorallocate($img,0,0,0); //字体 $font_ttf = './font/simhei.ttf'; //文字当前编码 $encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5')); //文字编码转UTF-8中文 $text = iconv($encode, "UTF-8",$str); //字体大小 $font_size = 20; $Galyon = 0; //获取文字盒子参数 $fontBox = imagettfbbox($font_size, $Galyon, $font_ttf, $text); //将文字添加到画布底部并居中 imagettftext($img, $font_size, $Galyon, ceil((430 - $fontBox[2]) / 2),430 + (60-$fontBox[1])/2, $color, $font_ttf, $text); //生成新的png图片 imagepng($img, ROOT_PATH . 'public/qrcode/template.png', null); imagedestroy($img); //目标图片 $dst_im = imagecreatefrompng(ROOT_PATH.'public/qrcode/template.png'); //原图片 $src_im = imagecreatefrompng($filename);//格式可改为通用形式imagecreatefromstring(file_get_contents($filename));filename为全路径+文件名例如ROOT_PATH . 'public/qrcode/template.png'
//原图片信息 $src_info = getimagesize($filename); //合并图片当前参数为原图拷贝到图片最左上角,像素为1:1,最后参数pct为0-100,100为不透明 imagecopymerge($dst_im,$src_im,0,0,0,0,$src_info[0],$src_info[1],100); imagepng($dst_im,$filename); return; }
效果: