GD库
1、Php中gd库的使用
Gd库是一个画图或处理有图片的函数库
 
2、使用gd库画图
GD库图像绘制的步骤
在PHP中创建一个图像应该完成如下所示的4个步骤:
1.创建一个背景图像(也叫画布),以后的操作都基于此背景图像。
2.在背景上绘制图像轮廓或输入文本。
3.输出最终图形
4.释放资源
代码:
<?php
//1. 创建画布
$im = p_w_picpathCreateTrueColor(200, 200); //建立空白画布背景
$white = p_w_picpathColorAllocate($im, 255, 255, 255); //设置画布颜色
$blue = p_w_picpathColorAllocate ($im, 0, 0, 64);
//2. 开始绘画
p_w_picpathFill($im, 0, 0, $blue); //绘制背景
p_w_picpathLine($im, 0, 0, 200, 200, $white); //画线
p_w_picpathString($im, 4, 50, 150, 'Sales', $white); //添加字串
//3. 输出图像
header('Content-type: p_w_picpath/png');
p_w_picpathPng ($im); //以 PNG 格式将图像输出
//4. 释放资源
p_w_picpathDestroy($im);
 
 
画布管理
 p_w_picpathcreate -- 新建一个基于调色板的图像
– resource p_w_picpathcreate ( int x_size, int y_size )
–本函数用来建立空新画布,参数为图片大小,单位为像素 (pixel)。支持256色。
 p_w_picpathcreatetruecolor -- 新建一个真彩×××像
– resource p_w_picpathcreatetruecolor ( int x_size, int y_size )
–新建一个真彩×××像画布 ,需要 GD 2.0.1 或更高版本,不能用于 GIF 文件格式。
 p_w_picpathdestroy -- 销毁一图像
– bool p_w_picpathdestroy ( resource p_w_picpath )
– p_w_picpathdestroy() 释放与 p_w_picpath 关联的内存
 
设置颜色
 p_w_picpathcolorallocate -- 为一幅图像分配颜色
–语法:int p_w_picpathcolorallocate ( resourcep_w_picpath, int red,int green, int blue )
 p_w_picpathcolorallocate() 返回一个标识符,代表了由给定的 RGB 成
分组成的颜色。red,green 和 blue 分别是所需要的颜色的红,
绿,蓝成分。这些参数是 0 到 255 的整数或者十六进制的 0x00
到 0xFF。p_w_picpathcolorallocate() 必须被调用以创建每一种用在
p_w_picpath 所代表的图像中的颜色。
$im =p_w_picpathcreatetruecolor(100, 100); //创建画布的大小为100x100
$red =p_w_picpathcolorallocate($im,255,0,0); //由十进制整数设置一个颜色
$white =p_w_picpathcolorallocate($im, 0xFF, 0xFF, 0xFF);// 十六进制方式
 
生成图片
 p_w_picpathgif -- 以 GIF 格式将图像输出到浏览器或文件
–语法:bool p_w_picpathgif (resource p_w_picpath[,string filename] )
 p_w_picpathjpeg -- 以 JPEG 格式将图像输出到浏览器或文件
–语法:bool p_w_picpathjpeg (resource p_w_picpath [,stringfilename [, int quality]])
 p_w_picpathpng -- 以 PNG 格式将图像输出到浏览器或文件
–语法:bool p_w_picpathpng (resource p_w_picpath[,string filename] )
 p_w_picpathwbmp -- 以 WBMP 格式将图像输出到浏览器或文件
–语法:bool p_w_picpathwbmp (resource p_w_picpath [,string filename [, intforeground]] )
 
3、画各种图形
p_w_picpathfill -- 区域填充
–语法:bool p_w_picpathfill(resource p_w_picpath,intx,int y, int color)
– p_w_picpathfill() 在 p_w_picpath 图像的坐标 x,y(图像左上角为 0, 0)处用color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。
 p_w_picpathsetpixel -- 画一个单一像素
–语法:bool p_w_picpathsetpixel ( resourcep_w_picpath, int x, int y, int color )
– p_w_picpathsetpixel() 在 p_w_picpath 图像中用 color 颜色在 x,y 坐标(图像左上角为 0,0)上画一个点。
 p_w_picpathline -- 画一条线段
–语法:bool p_w_picpathline ( resource p_w_picpath,int x1, int y1, int x2, inty2, int color )
– p_w_picpathline() 用 color 颜色在图像 p_w_picpath 中从坐标 x1,y1 到 x2,y2(图像左上角为 0, 0)画一条线段。
p_w_picpathrectangle -- 画一个矩形
–语法:bool p_w_picpathrectangle ( resourcep_w_picpath, int x1, int y1,int x2, int y2, int col )
– p_w_picpathrectangle() 用 col 颜色在 p_w_picpath 图像中画一个矩形,其左上角坐标为 x1, y1,右下角坐标为 x2, y2。图像的左上角坐标为 0, 0。
 p_w_picpathfilledrectangle -- 画一矩形并填充
–语法:bool p_w_picpathfilledrectangle (resource p_w_picpath, int x1, inty1, int x2, int y2, int color )
– p_w_picpathfilledrectangle() 在 p_w_picpath 图像中画一个用 color 颜色填充了的矩形,其左上角坐标为 x1,y1,右下角坐标为 x2,y2。0, 0 是图像的最左上角。
p_w_picpathellipse -- 画一个椭圆
–语法:bool p_w_picpathellipse ( resourcep_w_picpath, int cx, int cy, intw, int h, int color )
– p_w_picpathellipse() 在 p_w_picpath 所代表的图像中画一个中心为 cx,cy(图像左上角为 0, 0)的椭圆。w 和 h 分别指定了椭圆的宽度和高度,椭圆的颜色由 color 指定。
 p_w_picpathfilledellipse -- 画一椭圆并填充
–语法:bool p_w_picpathfilledellipse ( resourcep_w_picpath, int cx, intcy, int w, int h, int color )
– p_w_picpathfilledellipse() 在 p_w_picpath 所代表的图像中以 cx,cy(图像左上角为 0, 0)为中心画一个椭圆。w 和 h 分别指定了椭圆的宽和高。椭圆用 color 颜色填充。如果成功则返回
TRUE,失败则返回 FALSE。
p_w_picpatharc -- 画椭圆弧
– bool p_w_picpatharc ( resource p_w_picpath, int cx, int cy, int w, int h, int s,inte, int color )
– p_w_picpatharc() 以 cx,cy(图像左上角为 0, 0)为中心在 p_w_picpath 所代表的图像中画一个椭圆弧。w 和 h 分别指定了椭圆的宽度和高度,起始和结束点以 s 和 e 参数以角度指定。0°位于三点钟位置,以顺时针方向绘画。
 p_w_picpathfilledarc -- 画一椭圆弧且填充
– bool p_w_picpathfilledarc ( resource p_w_picpath, int cx, int cy, int w, int h,ints, int e, int color, int style )
– p_w_picpathfilledarc() 在 p_w_picpath 所代表的图像中以 cx,cy(图像左上角为 0, 0)画一椭圆弧。如果成功则返回 TRUE,失败则返回 FALSE。w 和 h 分别指定了椭圆的宽和高,s 和 e 参数以角度指定了起始和结束点。style 可以是下列值按位或(OR)后的值:
– IMG_ARC_PIE IMG_ARC_CHORD
– IMG_ARC_NOFILL IMG_ARC_EDGED
p_w_picpathstring -- 水平地画一行字符串
–语法:bool p_w_picpathstring ( resource p_w_picpath,int font, int x, int y,string s, int col )
– p_w_picpathstring() 用 col 颜色将字符串 s 画到 p_w_picpath 所代表的图像的 x,y 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果 font 是 1,2,3,4 或 5,则使用内置字体。
 p_w_picpathstringup -- 垂直地画一行字符串
–语法:bool p_w_picpathstringup ( resourcep_w_picpath, int font, int x, inty, string s, int col )
– p_w_picpathstring()用 col 颜色将字符串 s 垂直地画到 p_w_picpath 所代表的图像的 x , y 座标处(图像的左上角为 0, 0)。如果 font 是 1,2,3,4 或 5,则使用内置字体。
p_w_picpathchar -- 水平地画一个字符
–语法:bool p_w_picpathchar ( resource p_w_picpath,int font, int x, int y, string c,int color )
– p_w_picpathchar() 将字符串 c 的第一个字符画在 p_w_picpath 指定的图像中,其左上角位于 x,y(图像左上角为 0, 0),颜色为 color。如果 font 是1,2,3,4 或 5,则使用内置的字体(更大的数字对应于更大的字体)。
 p_w_picpathcharup -- 垂直地画一个字符
–语法:bool p_w_picpathcharup ( resource p_w_picpath,int font, int x, int y, stringc, int color )
– p_w_picpathcharup() 将字符 c 垂直地画在 p_w_picpath 指定的图像上,位于 x,y(图像左上角为 0, 0),颜色为 color。如果 font 为 1,2,3,4 或 5,则使用内置的字体。
 p_w_picpathttftext -- 用 TrueType 字体向图像写入文本
–语法 :array p_w_picpathttftext ( resource p_w_picpath, floatsize, float angle, intx, int y, int color, string fontfile, string text )
代码:
         //1创建资源(画布的大小)
         $img = p_w_picpathcreatetruecolor(200, 200);        
         //设置画布的颜色
         $white =  p_w_picpathcolorallocate($img, 0xFF, 0xFF, 0xFF);
         $red = p_w_picpathcolorallocate($img, 255, 0, 0);
         $blue = p_w_picpathcolorallocate($img, 0, 0, 0XFF);
         $pink = p_w_picpathcolorallocate($img, 0XFF, 0, 0XFF);
         $green =  p_w_picpathcolorallocate($img, 0, 0xFF, 0);
        
         p_w_picpathfill($img, 0, 0, $white);//填充画布颜色
         2、画各种图形     
         //画线
         p_w_picpathline($img, 0,0, 200,200, $blue);
         p_w_picpathline($img, 200, 0, 0, 200, $red);
 
         //画矩形
         p_w_picpathrectangle($img, 50, 50, 150, 150,$pink);
         p_w_picpathfilledrectangle($img, 75,75,125,125, $blue);
        
         //画圆
         p_w_picpathellipse($img, 50, 50, 100, 100,$red);
         p_w_picpathfilledellipse($img, 150, 150, 100,100, $red);
 
         //画弧形
         p_w_picpatharc($img, 150, 50, 100, 100,  -90, 0, $blue);
 
         //画一个字符串
         p_w_picpathstring($img, 5, 50, 150,"hello world", $blue);
         p_w_picpathstringup($img, 5, 50, 150,"hello world", $blue);
 
         //3. 画出各种图形,和写(画出)字
         p_w_picpathttftext($img, 30, 0, 10, 100,$green, "./simkai.ttf", "妹子漂亮吗?");
         p_w_picpathttftext($img, 30, 0, 13, 103,$red, "./simkai.ttf", "妹子漂亮吗?");
 
         //4保存,或输出给浏览, 写第二个参数就是保存
         header("Content-Type:p_w_picpaths/gif");
 
         p_w_picpathgif($img);
 
         //5. 释放资源
         p_w_picpathdestroy($img);
 
4、时钟代码:
//获取系统时间
         date_default_timezone_set("PRC");
 
         $h = date("H");
         $i = date("i");
         $s = date("s");
 
         //1 创建资源(画布的大小)
         $img = p_w_picpathcreatetruecolor(200, 250);        
         //设置画布的颜色
         $white =  p_w_picpathcolorallocate($img, 0xFF, 0xFF, 0xFF);
         $red = p_w_picpathcolorallocate($img, 255, 0, 0);
         $blue = p_w_picpathcolorallocate($img, 0, 0, 0XFF);
         $pink = p_w_picpathcolorallocate($img, 0XFF, 0, 0XFF);
         $green =  p_w_picpathcolorallocate($img, 0, 0xFF, 0);
         p_w_picpathfill($img, 0, 0, $white);
         //2. 制作各种图形
         p_w_picpathellipse($img, 100, 100, 190, 190,$blue);
         p_w_picpathfilledellipse($img, 100, 100, 4,4, $blue);
         p_w_picpathstring($img, 3, 95, 8,  "12", $blue);
         p_w_picpathstring($img, 3,180, 95,"03", $blue);
         p_w_picpathstring($img, 3, 95, 180,  "06", $blue);
         p_w_picpathstring($img, 3, 11, 95,  "09", $blue);
 
         //秒针
         $len = 80;
 
         $a = $len*sin(pi()/30*$s);
         $b = $len*cos(pi()/30*$s);
         $x = 100 + $a;
         $y = 100 - $b;
 
         p_w_picpathline($img, 100, 100, $x, $y,$red);
 
         //数字的时间
         p_w_picpathstring($img, 5, 20, 230,"NOW: {$h}:{$i}:{$s}", $red);
 
         //4保存,或输出给浏览, 写第二个参数就是保存
         header("Content-Type:p_w_picpath/gif");
         p_w_picpathgif($img);
 
         //5. 释放资源
         p_w_picpathdestroy($img);
 
5、验证码类
Reg.php
<?php
         session_start();
if(isset($_POST['dosubmit'])){
         if(strtoupper($_SESSION['code']) ==strtoupper($_POST['code']) ) {
                   echo "输入成功!<br>";
         }else{
                   echo "输入不对!<br>";
         }
}
?>
 
<body>
         <form action="reg.php"method="post">
                   username: <input type="text"name="username"> <br>
                   password: <inputtype="password" name="password"> <br>
                   code: <inputtype="text" onkeyup="if(this.value!=this.value.toUpperCase())this.value=this.value.toUpperCase()" size="6"name="code">
                   <imgsrc="code.php" onclick="this.src='code.php?'+Math.random()"/>  <br>
                   <inputtype="submit" name="dosubmit" value="登 录"> <br>
                  
         </form>
</body>
Code.php
<?php
         //开启session
         session_start();
         include "vcode.class.php";
         //构造方法
         $vcode = new Vcode(120, 30, 6);
         //将验证码放到服务器自己的空间保存一份
         $_SESSION['code'] =$vcode->getcode();
         //将验证码图片输出
         $vcode->outimg();
Vcode.class.php
<?php
         class Vcode {
                   private $width;    //宽
                   private $height;   //高
                   private $num;     //数量
                   private $code;    //验证码
                   private $img;     //图像的资源
 
                   //构造方法,三个参数
                   function__construct($width=80, $height=20, $num=4) {
                            $this->width =$width;
                            $this->height =$height;
                            $this->num =$num;
                            $this->code =$this->createcode(); //调用自己的方法
                   }
 
                   //获取字符的验证码,用于保存在服务器中
                   function getcode() {
                            return$this->code;
                   }
 
                   //输出图像
                   function outimg() {
                            //创建背景 (颜色, 大小, 边框)
                            $this->createback();
 
                            //画字 (大小, 字体颜色)
                            $this->outstring();
 
                            //干扰元素(点, 线条)
                           
                            $this->setdisturbcolor();
                            //输出图像
                            $this->printimg();
                   }
 
                   //创建背景
privatefunction createback() {
//创建资源
$this->img =p_w_picpathcreatetruecolor($this->width, $this->height);
//设置随机的背景颜色
$bgcolor =  p_w_picpathcolorallocate($this->img, rand(225,255), rand(225, 255), rand(225, 255));
//设置背景填充
p_w_picpathfill($this->img, 0, 0, $bgcolor);
//画边框
$bordercolor =  p_w_picpathcolorallocate($this->img, 0, 0, 0);
p_w_picpathrectangle($this->img, 0,0, $this->width-1, $this->height-1, $bordercolor);
                   }
                   //画字
privatefunction outstring() {
         for($i=0; $i<$this->num; $i++) {
         $color=p_w_picpathcolorallocate($this->img, rand(0, 128), rand(0, 128), rand(0, 128));
                                    
         $fontsize=rand(3,5);  //字体大小
 
         $x =3+($this->width/$this->num)*$i; //水平位置
         $y = rand(0,p_w_picpathfontheight($fontsize)-3);
 
         //画出每个字符
                                     p_w_picpathchar($this->img,$fontsize, $x, $y, $this->code{$i}, $color);
                            }
                   }
 
                   //设置干扰元素
privatefunction setdisturbcolor() {
         //加上点数
         for($i=0; $i<100; $i++) {
         $color=p_w_picpathcolorallocate($this->img, rand(0, 255), rand(0, 255), rand(0, 255));
         p_w_picpathsetpixel($this->img, rand(1,$this->width-2), rand(1, $this->height-2), $color);
                            }
         //加线条
for($i=0;$i<10; $i++) {
         $color=p_w_picpathcolorallocate($this->img, rand(0, 255), rand(0, 128), rand(0, 255));
     p_w_picpatharc($this->img,rand(-10,$this->width+10), rand(-10, $this->height+10), rand(30, 300), rand(30,300), 55,44, $color);
                            }
                   }
                   //输出图像
                   private function printimg() {
                            if (p_w_picpathtypes()& IMG_GIF) {
                                  header("Content-type: p_w_picpath/gif");
                                         p_w_picpathgif($this->img);
                            } elseif(function_exists("p_w_picpathjpeg")) {
                                  header("Content-type: p_w_picpath/jpeg");
                                  p_w_picpathgif($this->img);
                            } elseif(p_w_picpathtypes() & IMG_PNG) {
                                  header("Content-type: p_w_picpath/png");
                                         p_w_picpathgif($this->img);
                            }  else {
                                     die("No p_w_picpath support in this PHPserver");
                            }
                   }
                   //生成验证码字符串
                   private function createcode(){
                            $codes ="3456789abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXY";
                            $code ="";
                            for($i=0; $i <$this->num; $i++) {
                                     $code.=$codes{rand(0, strlen($codes)-1)};   
                            }
                            return $code;
                   }
                   //用于自动销毁图像资源
                   function __destruct() {
                            p_w_picpathdestroy($this->img);
                   }
 
         }
 
6、Php图片处理
图片背景管理 
图片缩放和裁剪 
添加图片水印 
图片旋转和翻转 
 
图片背景管理 
从指定的图片文件或 URL地址来新建一个图像。成功则返回一个图像标识符,失败时返回一个空字符串,并且输出一条错误信息。由于格式不同,则需要分别使用对应图片背景处理函数。 
–resource p_w_picpathcreatefrompng ( string filename ) 从 PNG 文件或 URL 新建一图像 
–resource p_w_picpathcreatefromjpeg ( string filename ) 从 JPEG 文件或 URL 新建一图像 
–resource p_w_picpathcreatefromgif ( string filename ) 从 GIF 文件或 URL 新建一图像 
–resource p_w_picpathcreatefromwbmp ( string filename ) 从 WBMP 文件或 URL 新建一图像 
 
其他图像处理函数: 
– intp_w_picpathsx ( resource p_w_picpath ) 取得图像宽度 
– intp_w_picpathsy ( resource p_w_picpath ) 取得图像高度 
– arraygetp_w_picpathsize ( string $filename [, array &$p_w_picpathinfo ] ) 取得图像大小、类型等信息
代码:
<?php
         function cimgstr($imgname, $string) {
                   list($width, $height, $type)=getp_w_picpathsize($imgname);
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   $img =$createp_w_picpath($imgname);
                   $red =  p_w_picpathcolorallocate($img, 0xFF, 0, 0);
                   $x =($width-p_w_picpathfontwidth(5)*strlen($string))/2;
                   $y =($height-p_w_picpathfontheight(5))/2;
                   p_w_picpathstring($img, 5, $x, $y,$string, $red);
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   $save($img,"new_".$imgname);
                   p_w_picpathdestroy($img);
         }
         cimgstr("dx.jpg","meizi");
         cimgstr("map.gif","meizi");
         cimgstr("cx.png","meize");
 
7、图片的缩放和剪切
bool p_w_picpathcopyresampled ( resource $dst_p_w_picpath , resource$src_p_w_picpath , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int$dst_h , int $src_w , int $src_h )
重采样拷贝部分图像并调整大小,是将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。成功时返回 TRUE, 或者在失败时返回 FALSE。其中dst_p_w_picpath 和 src_p_w_picpath 分别是目标图像和源图像的标识符。
缩放代码:
<?php
         function thumb($imgname, $width,$height) {
                   list($swidth, $sheight,$type)= getp_w_picpathsize($imgname);
 
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   //$createp_w_picpath =p_w_picpathcreatefromipeg;
                   //原图片
                   $imgsrc =$createp_w_picpath($imgname);
                   //目标资源
                   $dimg = p_w_picpathcreatetruecolor($width,$height);
                  
                   p_w_picpathcopyresampled($dimg,$imgsrc, 0, 0, 0, 0, $width, $height, $swidth, $sheight);
 
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   $save($dimg,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($dimg);
         }
         thumb("dx.jpg", 200, 200);
         thumb("map.gif", 200, 200);
         thumb("cx.png", 200, 200);
等比缩放代码:
<?php
         function thumb($imgname, $width,$height) {
                   list($swidth, $sheight,$type)= getp_w_picpathsize($imgname);
 
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   //原图片
                   $imgsrc =$createp_w_picpath($imgname);
                   //目标资源
                   $dimg =p_w_picpathcreatetruecolor($width, $height);
 
                   if ($width &&($swidth < $sheight)) {
                         $width = ($height / $sheight) * $swidth;
                   } else {
                       $height= ($width / $swidth) * $sheight;
                   }
 
                   p_w_picpathcopyresampled($dimg,$imgsrc, 0, 0, 0, 0, $width, $height, $swidth, $sheight);
        
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   $save($dimg,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($dimg);
         }
 
         thumb("dx.jpg", 200, 200);
         thumb("map.gif", 200, 200);
         thumb("cx.png", 200, 200);
 
剪切代码:
<?php
         function cut($imgname, $x, $y, $width,$height) {
                   list($swidth, $sheight,$type)= getp_w_picpathsize($imgname);
 
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   //原图片
                   $imgsrc =$createp_w_picpath($imgname);
                   //目标资源
                   $dimg =p_w_picpathcreatetruecolor($width, $height);
 
                   p_w_picpathcopyresampled($dimg,$imgsrc, 0, 0, $x, $y, $width, $height, $width, $height);
                  
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   $save($dimg,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($dimg);
         }
 
         cut("dx.jpg",50,50, 200,200);
         cut("map.gif",50,50, 200,200);
         cut("cx.png",50,50, 200,200);
 
8、添加图片水印
bool p_w_picpathcopy( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x ,int $src_y , int $src_w , int $src_h )
–拷贝图像的一部分(也就是图片合成)。 
–将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。
图片水印代码:
<?php
         function watermark($imgname,$watername) {
                   list($swidth, $sheight,$type)= getp_w_picpathsize($imgname);    //原图
                   list($wwidth, $wheight,$wtype)= getp_w_picpathsize($watername);  //水印
 
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath = "p_w_picpathcreatefrom".$types[$type];
                   $createp_w_picpathw ="p_w_picpathcreatefrom".$types[$wtype];
                   //原图片
                   $imgsrc =$createp_w_picpath($imgname);   //原图
 
                   $wimg =$createp_w_picpathw($watername);  //水印
 
                   $x = rand(3,$swidth-$wwidth);
                   $y = rand(3,$sheight-$wheight);
 
                   p_w_picpathcopy($imgsrc, $wimg, $x,$y, 0, 0, $wwidth, $wheight);
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   $save($imgsrc,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($wimg);
         }
         watermark("dx.jpg","php.gif");
         watermark("cx.png","php.gif");
文字水印代码:
<?php
         function watermark($imgname, $string) {
                   list($swidth, $sheight,$type)= getp_w_picpathsize($imgname);
 
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   //原图片
                   $imgsrc = $createp_w_picpath($imgname);
 
                   $white =p_w_picpathcolorallocate($imgsrc, 200,200, 200);
                   $green =p_w_picpathcolorallocate($imgsrc, 0,200, 0);
 
                   $x = rand(3,$swidth-strlen($string)*p_w_picpathfontwidth(5));
                   $y = rand(3,$sheight-p_w_picpathfontheight(5)-2);
 
                   p_w_picpathstring($imgsrc, 5, $x, $y,$string, $white);
                   p_w_picpathstring($imgsrc, 5, $x+1,$y+1, $string, $green);
                  
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   $save($imgsrc,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
         //      p_w_picpathdestroy($dimg);
         }
         watermark("dx.jpg","meizi");
         watermark("cx.png","meize");
 
9、图片旋转和翻转
resource p_w_picpathrotate ( resource $src_im , float $angle , int
$bgd_color[, int $ignore_transparent ] )
用给定角度旋转图像
将 src_im 图像用给定的angle角度旋转。bgd_color指定了旋转后没有覆盖到的部分的颜色。
旋转的中心是图像的中心。旋转后的图像会按比例缩小以适合目标图像的大小边缘不被剪去。
如果 ignore_transparent 被设为非零值,则透明色会被忽略(否则会被保留)。
旋转代码:
<?php
         function xz($imgname, $jd) {
                   list($swidth, $sheight,$type)= getp_w_picpathsize($imgname);    //原图
        
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   $imgsrc =  $createp_w_picpath($imgname);
        
                   //旋转
                   $new = p_w_picpathrotate($imgsrc,$jd, 0);
 
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   //保存
                   $save($new,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($new);
         }
         xz("php.gif", 90);
 
y轴旋转代码:
<?php
         //按y轴翻转
         function trun_y($imgname) {
                   list($width, $height, $type)=getp_w_picpathsize($imgname);    //原图
        
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   $imgsrc =  $createp_w_picpath($imgname);
 
                   $new =p_w_picpathcreatetruecolor($width, $height);   
                   //循环每次一个像素
                   for($x=0; $x<$width; $x++){
                            p_w_picpathcopy($new,$imgsrc, $width-$x-1, 0, $x,0, 1, $height);        
                   }
 
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   //保存
                   $save($new, "new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($new);
         }
         trun_y("cx.png");
x轴旋转代码:
<?php
         //按x轴翻转
         function trun_x($imgname) {
                   list($width, $height, $type)=getp_w_picpathsize($imgname);    //原图
        
                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");
 
                   //变量函数
                   $createp_w_picpath ="p_w_picpathcreatefrom".$types[$type];
                   $imgsrc =  $createp_w_picpath($imgname);
 
                   $new =p_w_picpathcreatetruecolor($width, $height);   
                   //循环每次一个像素
                   for($y=0; $y<$height;$y++) {
                            p_w_picpathcopy($new,$imgsrc, 0, $height-$y-1, 0,$y, $width, 1);        
                   }
                  
                   //变量函数
                   $save ="p_w_picpath".$types[$type];
                   //保存
                   $save($new,"new_".$imgname);
                   p_w_picpathdestroy($imgsrc);
                   p_w_picpathdestroy($new);
         }
         trun_x("cx.png");
        
10、图像处理类
使用类代码:
<?php
         //包含这个类p_w_picpath.class.php
         include "p_w_picpath.class.php";
 
         $img = new Image("./p_w_picpaths");
/*
         echo $img->thumb("dx.jpg",1000, 1000, "th2_")."<br>";
         echo $img->thumb("dx.jpg",800, 800, "th3_")."<br>";
 */
/*
         echo$img->watermark("dx.jpg", "php.gif", 0,"wa0_")."<br>";  
         echo$img->watermark("dx.jpg", "php.gif", 1,"wa1_")."<br>";            
 */  
 
         // 122   104   104 108
         echo $img->cut("cx.png",122, 104, 104, 108);
验证码类:
<?php
         /**
                   file: p_w_picpath.class.php 类名为Image
                   图像处理类,可以完成对各种类型的图像进行缩放、加图片水印和剪裁的操作。
         */
         class Image {
                   /* 图片保存的路径 */
                   private $path;                                  
 
                   /**
                    * 实例图像对象时传递图像的一个路径,默认值是当前目录
                    * @param      string        $path        可以指定处理图片的路径
                    */
                   function__construct($path="./"){
                            $this->path =rtrim($path,"/")."/";
                   }
                  
                   /**
                    * 对指定的图像进行缩放
                    * @param      string        $name      是需要处理的图片名称
                    * @param      int    $width               缩放后的宽度
                    * @param      int    $height              缩放后的高度
                    * @param      string        $qz            是新图片的前缀
                    * @return      mixed                          是缩放后的图片名称,失败返回false;
                    */
                   function thumb($name, $width,$height,$qz="th_"){
                            /* 获取图片宽度、高度、及类型信息 */
                            $imgInfo =$this->getInfo($name);                                
                            /* 获取背景图片的资源 */
                            $srcImg = $this->getImg($name,$imgInfo);                         
                            /* 获取新图片尺寸 */
                            $size =$this->getNewSize($name,$width, $height,$imgInfo);      
                            /* 获取新的图片资源 */
                            $newImg =$this->kidOfImage($srcImg, $size,$imgInfo);  
                            /* 通过本类的私有方法,保存缩略图并返回新缩略图的名称,以"th_"为前*/
                            return$this->createNewImage($newImg, $qz.$name,$imgInfo);   
                   }
                  
                   /**
* 为图片添加水印
* @paramstring $groundName背景图片,即需要加水印的图片,暂只支持GIF,JPG,PNG格式 
* @param string$waterName       图片水印,即作为水印的图片,暂只支持GIF,JPG,PNG格式
* @param        int    $waterPos                 水印位置,有10种状态,0为随机位置; 
*                                                                       1为顶端居左,2为顶端居中,3为顶端居右; 
*                                                                       4为中部居左,5为中部居中,6为中部居右; 
*                                                                        7为底端居左,8为底端居中,9为底端居右; 
* @param        string        $qz            加水印后的图片的文件名在原文件名前面加上这个前缀
* @return        mixed                                   是生成水印后的图片名称,失败返回false
*/
                   functionwaterMark($groundName, $waterName, $waterPos=0, $qz="wa_"){
                            /*获取水印图片是当前路径,还是指定了路径*/
                            $curpath= rtrim($this->path,"/")."/";
                            $dir= dirname($waterName);
                            if($dir== "."){
                                     $wpath= $curpath;
                            }else{
                                     $wpath= $dir."/";
                                     $waterName= basename($waterName);
                            }
                           
                            /*水印图片和背景图片必须都要存在*/
if(file_exists($curpath.$groundName)&& file_exists($wpath.$waterName)){
                   $groundInfo= $this->getInfo($groundName);                        //获取背景信息
                   $waterInfo= $this->getInfo($waterName, $dir);                //获取水印图片信息
                   /*如果背景比水印图片还小,就会被水印全部盖住*/
                   if(!$pos= $this->position($groundInfo, $waterInfo, $waterPos)){
                                               echo'水印不应该比背景图片小!';
                                               returnfalse;
                                     }
 
                   $groundImg= $this->getImg($groundName, $groundInfo);   //获取背景图像资源
                   $waterImg= $this->getImg($waterName, $waterInfo, $dir); //获取水印图片资源  
                                    
                   /*调用私有方法将水印图像按指定位置复制到背景图片中 */
                   $groundImg= $this->copyImage($groundImg, $waterImg, $pos, $waterInfo);
         /*通过本类的私有方法,保存加水图片并返回新图片的名称,默认以"wa_"为前缀 */
         return$this->createNewImage($groundImg, $qz.$groundName, $groundInfo);
                                    
                            }else{
                                     echo'图片或水印图片不存在!';
                                     returnfalse;
                            }
                   }
                   /**
                   *在一个大的背景图片中剪裁出指定区域的图片
                   *@param        string        $name      需要剪切的背景图片
                   *@param        int    $x                        剪切图片左边开始的位置
                   *@param        int    $y                        剪切图片顶部开始的位置
                   *@param        int    $width               图片剪裁的宽度
                   *@param        int    $height              图片剪裁的高度
                   *@param        string        $qz            新图片的名称前缀
                   *@return        mixed                          裁剪后的图片名称,失败返回false;
                   */
function cut($name, $x, $y, $width, $height,$qz="cu_"){
$imgInfo=$this->getInfo($name);                 //获取图片信息
/* 裁剪的位置不能超出背景图片范围 */
if( (($x+$width) >$imgInfo['width']) || (($y+$height) > $imgInfo['height'])){
echo "裁剪的位置超出了背景图片范围!";
return false;
}
 
$back = $this->getImg($name,$imgInfo);         //获取图片资源
/* 创建一个可以保存裁剪后图片的资源 */
$cutimg = p_w_picpathcreatetruecolor($width,$height);
/* 使用p_w_picpathcopyresampled()函数对图片进行裁剪 */
p_w_picpathcopyresampled($cutimg, $back,0, 0, $x, $y, $width, $height, $width, $height);
p_w_picpathdestroy($back);
/* 通过本类的私有方法,保存剪切图并返回新图片的名称,默认以"cu_"为前缀 */
return $this->createNewImage($cutimg,$qz.$name,$imgInfo);
}
 
/* 内部使用的私有方法,用来确定水印图片的位置 */
private function position($groundInfo,$waterInfo, $waterPos){
/* 需要加水印的图片的长度或宽度比水印还小,无法生成水印 */
         if(($groundInfo["width"]<$waterInfo["width"]) ||($groundInfo["height"]<$waterInfo["height"]) ) {
                                     returnfalse;
                            }
                            switch($waterPos){
                                     case1:                        //1为顶端居左 
                                               $posX= 0;
                                               $posY= 0;
                                               break;
                                     case2:                        //2为顶端居中 
                                               $posX= ($groundInfo["width"] - $waterInfo["width"]) / 2;
                                               $posY= 0;
                                               break;
                                     case3:                        //3为顶端居右 
                                               $posX= $groundInfo["width"] - $waterInfo["width"];
                                               $posY= 0;
                                               break;
                                     case4:                        //4为中部居左 
                                               $posX= 0;
                                               $posY= ($groundInfo["height"] - $waterInfo["height"]) / 2;
                                               break;
                                     case5:                        //5为中部居中 
                                               $posX= ($groundInfo["width"] - $waterInfo["width"]) / 2;
                                               $posY= ($groundInfo["height"] - $waterInfo["height"]) / 2;
                                               break;
                                     case6:                        //6为中部居右 
                                               $posX= $groundInfo["width"] - $waterInfo["width"];
                                               $posY= ($groundInfo["height"] - $waterInfo["height"]) / 2;
                                               break;
                                     case7:                        //7为底端居左 
                                               $posX= 0;
                                               $posY= $groundInfo["height"] - $waterInfo["height"];
                                               break;
                                     case8:                        //8为底端居中 
                                               $posX= ($groundInfo["width"] - $waterInfo["width"]) / 2;
                                               $posY= $groundInfo["height"] - $waterInfo["height"];
                                               break;
                                     case9:                        //9为底端居右 
                                               $posX= $groundInfo["width"] - $waterInfo["width"];
                                               $posY= $groundInfo["height"] - $waterInfo["height"];
                                               break;
                                     case0:
                                     default:             //随机 
                                               $posX= rand(0,($groundInfo["width"] - $waterInfo["width"]));
                                               $posY= rand(0,($groundInfo["height"] - $waterInfo["height"]));
                                               break;
                            }
                            returnarray("posX"=>$posX, "posY"=>$posY);
                   }
 
                  
                   /*内部使用的私有方法,用于获取图片的属性信息(宽度、高度和类型) */
                   privatefunction getInfo($name, $path=".") {
                            $spath= $path=="." ? rtrim($this->path,"/")."/" :$path.'/';
                           
                            $data= getp_w_picpathsize($spath.$name);
                            $imgInfo["width"]   = $data[0];
                            $imgInfo["height"]  = $data[1];
                            $imgInfo["type"]      = $data[2];
 
                            return$imgInfo;               
                   }
 
                   /*内部使用的私有方法, 用于创建支持各种图片格式(jpg,gif,png三种)资源  */
                   privatefunction getImg($name, $imgInfo, $path='.'){
                           
                            $spath= $path=="." ? rtrim($this->path,"/")."/" :$path.'/';
                            $srcPic= $spath.$name;
                           
                            switch($imgInfo["type"]) {
                                     case1:                                           //gif
                                               $img= p_w_picpathcreatefromgif($srcPic);
                                               break;
                                     case2:                                           //jpg
                                               $img= p_w_picpathcreatefromjpeg($srcPic);
                                               break;
                                     case3:                                           //png
                                               $img= p_w_picpathcreatefrompng($srcPic);
                                              break;
                                     default:
                                               returnfalse;
                                               break;
                            }
                            return$img;
                   }
                  
                   /*内部使用的私有方法,返回等比例缩放的图片宽度和高度,如果原图比缩放后的还小保持不变 */
                   privatefunction getNewSize($name, $width, $height, $imgInfo){         
                            $size["width"]= $imgInfo["width"];         //原图片的宽度
                            $size["height"]= $imgInfo["height"];        //原图片的高度
                           
                            if($width< $imgInfo["width"]){
$size["width"]=$width;  //缩放的宽度如果比原图小才重新设置宽度
                            }
 
                            if($height< $imgInfo["height"]){
                                     $size["height"]= $height;  //缩放的高度如果比原图小才重新设置高度
                            }
                            /*等比例缩放的算法 */
if($imgInfo["width"]*$size["width"]> $imgInfo["height"] * $size["height"]){
         $size["height"]=round($imgInfo["height"]*$size["width"]/$imgInfo["width"]);
                            }else{
         $size["width"]= round($imgInfo["width"]*$size["height"]/$imgInfo["height"]);
                            }
                            return$size;
                   }       
                  
                   /*内部使用的私有方法,用于保存图像,并保留原有图片格式 */
                   privatefunction createNewImage($newImg, $newName, $imgInfo){
                            $this->path= rtrim($this->path,"/")."/";
                            switch($imgInfo["type"]) {
                                  case1:                                 //gif
                                               $result= p_w_picpathGIF($newImg, $this->path.$newName);
                                               break;
                                     case2:                                 //jpg
                                               $result= p_w_picpathJPEG($newImg,$this->path.$newName); 
                                               break;
                                     case3:                                 //png
                                               $result= p_w_picpathPng($newImg, $this->path.$newName); 
                                               break;
                            }
                            p_w_picpathdestroy($newImg);
                            return$newName;
                   }
 
                   /*内部使用的私有方法,用于加水印时复制图像 */
private function copyImage($groundImg,$waterImg, $pos, $waterInfo){
     p_w_picpathcopy($groundImg,$waterImg, $pos["posX"], $pos["posY"], 0, 0,$waterInfo["width"],$waterInfo["height"]);
                            p_w_picpathdestroy($waterImg);
                            return$groundImg;
                   }
 
/* 内部使用的私有方法,处理带有透明度的图片保持原样 */
                   privatefunction kidOfImage($srcImg, $size, $imgInfo){
                            $newImg= p_w_picpathcreatetruecolor($size["width"], $size["height"]);              
                            $otsc= p_w_picpathcolortransparent($srcImg);                                           
                            if($otsc >= 0 && $otsc < p_w_picpathcolorstotal($srcImg)) {                 
                                    $transparentcolor = p_w_picpathcolorsforindex($srcImg, $otsc );
                                     $newtransparentcolor = p_w_picpathcolorallocate(
                                            $newImg,
                                             $transparentcolor['red'],
                                          $transparentcolor['green'],
                                            $transparentcolor['blue']
                                    );
                                    p_w_picpathfill( $newImg, 0, 0, $newtransparentcolor);
                                    p_w_picpathcolortransparent( $newImg,$newtransparentcolor );
                            }
p_w_picpathcopyresized( $newImg, $srcImg, 0, 0, 0,0, $size["width"], $size["height"],$imgInfo["width"], $imgInfo["height"] );
                            p_w_picpathdestroy($srcImg);
                            return$newImg;
                   }
         }
微信扫一扫 、关注公众号
   不定时分享资料视频
