DAY59

 学前了解:

在PHP中可以通过GD库处理图像
创建一个图像应该完成如下所示的四个基本步骤:

一、创建图像

1.创建新的

imagecreatetruecolor()//新建一个真彩色图像

2.打开服务器或网络文件中已经存在的GIF,JPEG,PNG,WBMP格式图像

imagecreatefromjpeg()
imagecreatefrompng()
imagecreatefromgif() 
imagecreatefromwbmp() 
创建或者打开失败的时候会返回空字符串,并且输出一条错误信息。 
imagesx()//输出画布宽度 
imagesy()//输出画布高度 
getimagesize()//取得图像大小


二、绘制图像 
图像创建完成以后,就可以通过这个图像资源,使用各种画像函数设置图像的颜 色、填充图像、画点、线段、以及向图像的添加文本等

1.imagecolorallocate()//分配颜色 
2.imagefill()//区域填充 
3.imagesetpixel()//画一个单一像素 
4.imageline()//画一条线段 
5.imagerectangle()//画一个矩形 
6.imagestring()//水平地画一行字符串 
7.imagettftext()//用 TrueType 字体向图像写入文本 
8.imagettfbbox()//计算 TrueType 文字所占区域 
9.imagecopy()//拷贝图像的一部分 
10.imagecopymerge()//拷贝并合并图像的一部分 
11.imagecopyresampled()//重采样拷贝部分图像并调整大小

三、生成图像 
header() 
imagegif() 
imagejpeg()
imagepng() 
imagewbmp()


3.输出图像
header函数注意点
在该函数之前,不能输出任何内容

在我们的PHP代码 的函数里面,我们使用的/开头的路径 这个/不是指 web根目录,而是操作系统的 文件的根目录!

四、释放资源

imagedestroy() //销毁一图像

<?php
header('Content-type:image/jpeg');
$width=120;
$height=40;
$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++){
    $string.=$element[rand(0,count($element)-1)];
}
$img=imagecreatetruecolor($width, $height);//新建一个真彩色图像
$colorBg=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));//为一幅图像分配颜色
$colorBorder=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
$colorString=imagecolorallocate($img,rand(10,100),rand(10,100),rand(10,100));
imagefill($img,0,0,$colorBg);//区域填充
imagerectangle($img,0,0,$width-1,$height-1,$colorBorder);//画一个矩形
for($i=0;$i<100;$i++){
    imagesetpixel($img,rand(0,$width-1),rand(0,$height-1),imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200)));
}
for($i=0;$i<3;$i++){
    imageline($img,rand(0,$width/2),rand(0,$height),rand($width/2,$width),rand(0,$height),
imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200)));
}
//imagestring($img,5,0,0,'abcd',$colorString);
imagettftext($img,14,rand(-5,5),rand(5,15),rand(30,35),$colorString,'font/SketchyComic.ttf',$string);//用 TrueType 字体向图像写入文本
imagejpeg($img);//输出图象到浏览器或文件。
imagedestroy($img);//销毁一图像

原文地址:https://www.cnblogs.com/qianjilou/p/6939823.html