function addTextToImage($qrCode, $text) { // 假设 $qrCode 是通过某个生成小程序码的函数或方式获取的图像资源 // 获取小程序码的宽度和高度 $qrCodeWidth = imagesx($qrCode); $qrCodeHeight = imagesy($qrCode); // 增加底部白色区域的高度和文字内容 $bottomMargin = 40; // 可以根据需要调整空白区域的高度 $font = 18; // 字体大小,可以根据需要调整 $color = imagecolorallocate($qrCode, 0, 0, 0); // RGB 颜色值,这里是黑色,可以根据实际情况调整 // 创建一个新的图像资源,包括额外的底部空白和文字 $newImage = imagecreatetruecolor($qrCodeWidth, $qrCodeHeight + $bottomMargin); // 填充底部空白区域为白色 $white = imagecolorallocate($newImage, 255, 255, 255); imagefilledrectangle($newImage, 0, $qrCodeHeight, $qrCodeWidth, $qrCodeHeight + $bottomMargin, $white); // 在新图像上复制生成的小程序码 imagecopy($newImage, $qrCode, 0, 0, 0, 0, $qrCodeWidth, $qrCodeHeight); $fontfile=public_path().'/static/fonts/ttfs/arial.ttf'; if(!file_exists($fontfile)){ return false; } // 设置文字的位置 $textWidth = imagettfbbox($font, 0, $fontfile, $text); $textWidth = $textWidth[4] - $textWidth[0]; // 获取文字宽度 $textX = ($qrCodeWidth - $textWidth) / 2; // X 坐标居中 $textY = $qrCodeHeight + 20; // 文字距离底部空白的顶部距离,可以根据需要调整 // 添加文字到新的图像上 imagettftext($newImage, intval($font), 0, intval($textX), $textY, $color, $fontfile, $text); // 释放原始小程序码资源 imagedestroy($qrCode); return $newImage; }
调用的地方:
$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token; $data = array( 'scene' => $qrcode_id, 'page' => get_sys_config('pageurl'),//'',//'pages/index/codeRent', // 替换成你的小程序页面路径 'width' => 300, 'auto_color' => false, 'line_color' => array('r' => 0, 'g' => 0, 'b' => 0), 'is_hyaline' => false, ); $data_json = json_encode($data); $response = Http::curl_post($url, $data_json); $file_path = '/storage/qrcode/' . date("Y-m-d"); // 替换成你存储图片的路径 $file_name = date("YmdHis") . '_' . $qrcode_id . '.png'; //只是做了个目录/的处理,没啥其他用 $destDir = Filesystem::fsFit(public_path() . $file_path); if (!is_dir($destDir)) { mkdir($destDir, 0777, true); } try { $result = imagecreatefromstring($response); if ($result) { // 加文字到小程序码上 $newImage = addTextToImage($result, $lockInfo['lock_barcode']); // 保存图像到本地文件 $imagePath = $destDir . '/' . $file_name; // 替换为你希望保存的路径和文件名 // 保存为 PNG 格式 imagepng($newImage, $imagePath); // 释放新图像资源 imagedestroy($newImage); } else { new Exception('无法生成小程序码'); } self::update(['qr_image' => $file_path.'/'.$file_name], ['qr_id' => $qrcode_id]); } catch (FileException $e) { throw new FileException($e->getMessage()); } return $file_path . '/' . $file_name;
发表评论 取消回复