为此,我们正在与GD library合作。
"PHP 不仅限于创建 HTML 输出。它还可以用于
在各种不同的图像中创建和操作图像文件
格式,包括 GIF、PNG、JPEG、WBMP 和 XPM。更
方便,PHP 可以直接将图像流输出到浏览器。你
需要使用图像函数的GD library 编译PHP
这工作。 GD 和 PHP 可能还需要其他库,具体取决于
您要使用的图像格式。”
您可以使用 PHP 中的图像函数来获取 JPEG、GIF、PNG、SWF、TIFF 和 JPEG2000 图像的大小。
以下代码示例演示了如何使用 GD 库对图像进行动态水印。此处演示的为上传的图片添加水印的方法是在原始图片上叠加另一张图片,最好是透明的 PNG 图片。
PHP 提供了一组丰富的函数来动态创建和更改图像。这些函数需要 GD 库,该库从 4.3 版开始与 PHP 捆绑在一起。
HTML 表单需要一个文件上传元素:<input type="file">. 您还必须为表单指定正确的编码类型:enctype="multipart/form-data"。
/ link to the font file no the server
$fontname = 'font/Capriola-Regular.ttf';
// controls the spacing between text
$i=30;
//JPG image quality 0-100
$quality = 85;
function create_image($user){
global $fontname;
global $quality;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";
// if the file already exists dont create it again just serve up the original
if (!file_exists($file)) {
// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");
// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);
// this defines the starting height for the text block
$y = imagesy($im) - $height - 365;
// loop through the array and write the text
foreach ($user as $value){
// center the text in our image - returns the x value
$x = center_text($value['name'], $value['font-size']);
imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
// add 32px to the line height for the next text block
$i = $i+32;
}
// create the image
imagejpeg($im, $file, $quality);
}
return $file;
}
function center_text($string, $font_size){
global $fontname;
$image_width = 800;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);
return ceil(($image_width - $dimensions[4]) / 2);
}
$user = array(
array(
'name'=> 'Slimen Tunis',
'font-size'=>'25',
'color'=>'black'),
array(
'name'=> 'Web developer',
'font-size'=>'16',
'color'=>'grey'),
array(
'name'=> 'SlimenTunis@webdeveloper.com',
'font-size'=>'13',
'color'=>'green'
)
);
// run the script to create the image
$filename = create_image($user);
这里我们有两个函数让它尽可能简单。要运行代码,只需将 $user 数组数据传递给函数,它会将新图像保存在服务器上的文件夹“covers”中。该函数返回文件 url,因此您只需将其回显到图像标签中,如下所示。查看演示,您可以在其中创建自己的。
$filename = create_image($user);
<img src="<?=$filename;?>" width="800" height="600"/>