笔记
案例
图像的绘制
实训
验证码1
<?php
//1.创建画布
$img=imagecreatetruecolor(120,40);//建立空白背景
//2.设置背景颜色
$gray=imagecolorallocate($img,200,200,200);//设置绘画颜色
//3.将背景颜色填充到真彩画布上
imagefill($img,0,0,$gray);//绘制背景
//4.绘制图像
//绘制干扰点
for ($i=0;$i<30;$i++) {
$color=imagecolorallocate($img,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($img,rand(0,120),rand(0,40),$color);
}
//绘制干扰线
for ($j=0;$j<10;$j++) {
$color=imagecolorallocate($img,rand(50,200),rand(50,200),rand(50,200));
imageline($img,rand(0,120),rand(0,40),rand(0,120),rand(0,40),$color);
}
//绘制文字
$str=’0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ’;
$newstr=str_shuffle($str);//打乱字符串
$newstr1=substr($newstr,0,4);//截取字符串
for ($z=0;$z<4;$z++) {
imagettftext($img,20,rand(-20,20),($z*20+15),30,$color,’trebuc.ttf’,$newstr1[$z]);
}
//5.设置图像格式,
header(‘content-type:image/png’);
//6.输出图像
imagepng($img);//把图像用png格式输出
//7.释放资源
imagedestroy($img);
?>
验证码2
<?php
//1.创建画布
$img=imagecreatetruecolor(120,40);//建立空白背景
//2.设置背景颜色
$gray=imagecolorallocate($img,200,200,200);//设置绘画颜色
//3.将背景颜色填充到真彩画布上
imagefill($img,0,0,$gray);//绘制背景
//4.绘制图像
//绘制干扰点
for ($i=0;$i<30;$i++) {
$color=imagecolorallocate($img,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($img,rand(0,120),rand(0,40),$color);
}
//绘制干扰线
for ($j=0;$j<10;$j++) {
$color=imagecolorallocate($img,rand(50,200),rand(50,200),rand(50,200));
imageline($img,rand(0,120),rand(0,40),rand(0,120),rand(0,40),$color);
}
//绘制文字
$str=’0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ’;
$newstr=str_shuffle($str);//打乱字符串
$vcode=substr($newstr,0,4);//截取字符串
imagestring($img,5,40,10,$vcode,$color);
//5.设置图像格式
header(‘content-type:image/png’);
//6.输出图像
imagepng($img);//把图像用png格式输出
//7.释放资源
imagedestroy($img);
?>
水印
<?php
//1.用户上传的照片
$dst=’1.jpeg’;
$src=’2.png’;
//2.将图片读取到画布上
$imagedet=imagecreatefromjpeg($dst);
$imagesrc=imagecreatefrompng($src);
//3.制作水印
imagecopymerge($imagedet,$imagesrc,0,0,0,0,270,250,50);
//4.设置图像格式,
header(‘content-type:image/jpeg’);
//5.输出图像
imagejpeg($imagedet);//把图像用jpeg格式输出
//6.释放资源
imagedestroy($imagedet);
?>