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; }
效果: