<?php
header('Content-type:image/jpeg');
$width=120;
$height=40;
$img = imagecreatetruecolor($width, $height);
//使字符串(字母)可以随机变化
//把要用的字母保存在数组$element中
$element=array('a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
//初始化变量
$string='';
for ($i=0;$i<5;$i++){
//.是连接的意思
//rand(0,count($element)-1)是随机下标
$string.=$element[rand(0,count($element)-1)];
}
//数字越大颜色越浅($img, $red, $green, $blue)
//$color_bg = imagecolorallocate($img, 200, 200, 200);
//rand(200,255):使得颜色在200到255之间随机变化
//图像的颜色
$color_bg = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255));
//矩形边框的颜色
$color_border = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255));
//像素、线的颜色
$color_xs = imagecolorallocate($img, rand(100,200), rand(100,200), rand(100,200));
//字符串的颜色
$color_string = imagecolorallocate($img, rand(10,100), rand(10,100), rand(100,200));
//填充颜色
imagefill($img, 0, 0, $color_bg);
//1. 在图像内画一个矩形边框(可有可无)
// $width-1 也就是120-1 = 119
// $height-1 也就是40-1 = 39
imagerectangle($img, 0, 0, $width-1, $height-1, $color_border);
//2. 画一个单一像素
imagesetpixel($img, rand(0,$width-1), rand(0,$height-1), $color_xs);
//多画几个点
for($i=0; $i<100; $i++) {
imagesetpixel($img, rand(0,$width-1), rand(0,$height-1), $color_xs);
}
/*
画一条线,随机从起点的左半边开始到终点的右半边
imageline($img, rand(0, ($width-1)/2), rand(0, ($height-1)/2), rand(($width-1)/2, $width), rand(($height-1)/2, $height), $color_xs);
*/
//3. 多画几条线
for($i=0; $i<2; $i++) {
imageline($img, rand(0, ($width-1)/2), rand(0, ($height-1)/2), rand(($width-1)/2, $width), rand(($height-1)/2, $height), $color_xs);
}
/*
水平地画一行字符串
imagestring($img, 5, 0, 0, 'ABCD', $color_string);
*/
//4. 画一些自定义字体的字母
//18是字体的大小
//2是倾斜角度
//5, 35是x和y轴的坐标
imagettftext($img, 18, 2, 5, 35, $color_string, 'font/Ske.ttf', $string);
//生成图像
imagejpeg($img);
//释放内存
imagedestroy($img);
?>
–4. 字体所在的文件位置:
–最终效果图: