名片背景
2 用户信息输入
信息输入
3 名片生成(点击Continue之后)
名片生成
步骤
在一切开始之前,请使用phpinfo() command
来确认GD库已安装。
首先,我们要做的事情很简单,新建一个PHP文件,就叫它main.php吧。
在main.php中,理论上我们需要以下几行代码(本代码基于CakePHP 3):
<?php//创建一个表单提供用户输入功能echo $this->Form->create();//只保留value属性,其他属性已省略echo $this->Form->input("First Name",["value" => $firstname, "..." => "...", ...]);echo $this->Form->input("Last Name",["value" => $lastname, "..." => "...", ...]);echo $this->Form->input("City",["value" => $city, "..." => "...", ...]);echo $this->Form->input("State",["value" => $state, "..." => "...", ...]);/** 将img标签指向一个叫做image.php的PHP文件。 * 所有的用户输入信息将以URL的形式保存在img标签的src属性中, * 在表格提交后即可被image.php通过GET获取。* 所有变量已通过PHP自带strtoupper函数转换为大写。*/echo $this->Html->image("image.php?first=".strtoupper($firstname)."&last=".strtoupper($lastname)."&location=".strtoupper($city)." ".strtoupper($state), ["fullBase" => true]);/** 上面的代码相当于:* <img src="image.php?first=名&last=姓&location=城市" />*///表单提交echo $this->Form->button("CONTINUE", ["type" => "submit"]); //关闭表单$this->Form->end();接下来,就是创建Where amazing happens的image.php了。包括图片设置,获取用户信息,将文字信息添加到图片上,所有的一切都将在这一步完成。
<?php// header() 函数向客户端发送原始的 HTTP 报头。header("Content-type: image/jpeg");// 由文件或 URL 创建一个新图象,这里的text.jpg就是效果1显示的预设图片$rImg = ImageCreateFromJPEG("test.jpg"); // 为一幅图像分配颜色$cor = imagecolorallocate($rImg, 0, 0, 0);// 我们可以自定义与图片结合的文字字体$font = "./arial.ttf";// 设置最终生成图片的宽度以及文字相对于图片所在的高度$imgWidthSetting = 676;$textHeightOffset = 220;// 解码main.php里img标签已编码的URL字符串,包括first, last以及location$first = urldecode($_GET["first"]);$last = urldecode($_GET["last"]);$location = urldecode($_GET["location"]);/** 取得需要向图片上添加的文本的范围。imagettfbbox() 返回一个含有8个* 单元的数组表示了文本外框的四个角。*/$width_first = imagettfbbox(60, 0, $font, $first);$width_last = imagettfbbox(70, 0, $font, $last);$width_location = imagettfbbox(35, 0, $font, $location);// 进一法取整, $width_变量[2]代表右下角X坐标位置$x_first = ceil($imgWidthSetting - $width_first[2]);$x_last = ceil($imgWidthSetting - $width_last[2]); $x_location = ceil($imgWidthSetting - $width_location[2]);// 利用imagettftext()函数将文本“写入”图像imagettftext($rImg, 60, 0, $x_first, $textHeightOffset+120, $cor, $font, $first);imagettftext($rImg, 70, 0, $x_last, $textHeightOffset+210, $cor, $font, $last);imagettftext($rImg, 35, 0, $x_location, $textHeightOffset+290, $cor, $font, $location);// 输出图象到浏览器或文件,quality 为可选项,范围从 0(最差质量,文件更小)到 100(最佳质量,文件最大)imagejpeg($rImg,NULL,100); // Free up memory, imagedestroy() 释放与 image 关联的内存。imagedestroy($rImg);到这里,我们就完成了通过PHP把文字添加到图片上的所有步骤。当用户输入个人信息并提交表单后,通过image.php,效果3的名片就会自动生成。