开发者社区> 科技小能手> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

PHP系列(十)GD库

简介:
+关注继续查看

GD

1Phpgd库的使用

Gd库是一个画图或处理有图片的函数库

 

2、使用gd库画图

GD库图像绘制的步骤

PHP中创建一个图像应该完成如下所示的4个步骤:

1.创建一个背景图像(也叫画布),以后的操作都基于此背景图像。

2.在背景上绘制图像轮廓或输入文本。

3.输出最终图形

4.释放资源

代码:

<?php

//1. 创建画布

$im imageCreateTrueColor(200200); //建立空白画布背景

$white imageColorAllocate($im255255255); //设置画布颜色

$blue imageColorAllocate ($im0064);

//2. 开始绘画

imageFill($im00$blue); //绘制背景

imageLine($im00200200$white); //画线

imageString($im450150'Sales'$white); //添加字串

//3. 输出图像

header('Content-type: image/png');

imagePng ($im); //以 PNG 格式将图像输出

//4. 释放资源

imageDestroy($im);

 

 

画布管理

imagecreate -- 新建一个基于调色板的图像

 resource imagecreate ( int x_size, int y_size )

本函数用来建立空新画布,参数为图片大小,单位为像素 (pixel)。支持256色。

imagecreatetruecolor -- 新建一个真彩色图像

 resource imagecreatetruecolor ( int x_size, int y_size )

新建一个真彩色图像画布 ,需要 GD 2.0.1 或更高版本,不能用于 GIF 文件格式。

imagedestroy -- 销毁一图像

 bool imagedestroy ( resource image )

 imagedestroy() 释放与 image 关联的内存

 

设置颜色

imagecolorallocate -- 为一幅图像分配颜色

语法:int imagecolorallocate ( resourceimage, int red,int green, int blue )

imagecolorallocate() 返回一个标识符,代表了由给定的 RGB 

分组成的颜色。redgreen  blue 分别是所需要的颜色的红,

绿,蓝成分。这些参数是 0  255 的整数或者十六进制的 0x00

 0xFFimagecolorallocate() 必须被调用以创建每一种用在

image 所代表的图像中的颜色。

$im =imagecreatetruecolor(100, 100); //创建画布的大小为100x100

$red =imagecolorallocate($im,255,0,0); //由十进制整数设置一个颜色

$white =imagecolorallocate($im, 0xFF, 0xFF, 0xFF);// 十六进制方式

 

生成图片

imagegif --  GIF 格式将图像输出到浏览器或文件

语法:bool imagegif (resource image[,string filename] )

imagejpeg --  JPEG 格式将图像输出到浏览器或文件

语法:bool imagejpeg (resource image [,stringfilename [, int quality]])

imagepng --  PNG 格式将图像输出到浏览器或文件

语法:bool imagepng (resource image[,string filename] )

imagewbmp --  WBMP 格式将图像输出到浏览器或文件

语法:bool imagewbmp (resource image [,string filename [, intforeground]] )

 

3、画各种图形

imagefill -- 区域填充

语法:bool imagefill(resource image,intx,int y, int color)

 imagefill()  image 图像的坐标 xy(图像左上角为 0, 0)处用color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。

imagesetpixel -- 画一个单一像素

语法:bool imagesetpixel ( resourceimage, int x, int y, int color )

 imagesetpixel()  image 图像中用 color 颜色在 x坐标(图像左上角为 00)上画一个点。

imageline -- 画一条线段

语法:bool imageline ( resource image,int x1, int y1, int x2, inty2, int color )

 imageline()  color 颜色在图像 image 中从坐标 x1y1  x2y2(图像左上角为 0, 0)画一条线段。

imagerectangle -- 画一个矩形

语法:bool imagerectangle ( resourceimage, int x1, int y1,int x2, int y2, int col )

 imagerectangle()  col 颜色在 image 图像中画一个矩形,其左上角坐标为 x1, y1,右下角坐标为 x2, y2。图像的左上角坐标为 0, 0

imagefilledrectangle -- 画一矩形并填充

语法:bool imagefilledrectangle (resource image, int x1, inty1, int x2, int y2, int color )

 imagefilledrectangle()  image 图像中画一个用 color 颜色填充了的矩形,其左上角坐标为 x1y1,右下角坐标为 x2y20, 0 是图像的最左上角。

imageellipse -- 画一个椭圆

语法:bool imageellipse ( resourceimage, int cx, int cy, intw, int h, int color )

 imageellipse()  image 所代表的图像中画一个中心为 cxcy(图像左上角为 0, 0)的椭圆。 h 分别指定了椭圆的宽度和高度,椭圆的颜色由 color 指定。

imagefilledellipse -- 画一椭圆并填充

语法:bool imagefilledellipse ( resourceimage, int cx, intcy, int w, int h, int color )

 imagefilledellipse()  image 所代表的图像中以 cxcy(图像左上角为 0, 0)为中心画一个椭圆。 h 分别指定了椭圆的宽和高。椭圆用 color 颜色填充。如果成功则返回

TRUE,失败则返回 FALSE

imagearc -- 画椭圆弧

 bool imagearc ( resource image, int cx, int cy, int w, int h, int s,inte, int color )

 imagearc()  cxcy(图像左上角为 0, 0)为中心在 image 所代表的图像中画一个椭圆弧。 h 分别指定了椭圆的宽度和高度,起始和结束点以 s  e 参数以角度指定。0°位于三点钟位置,以顺时针方向绘画。

imagefilledarc -- 画一椭圆弧且填充

 bool imagefilledarc ( resource image, int cx, int cy, int w, int h,ints, int e, int color, int style )

 imagefilledarc()  image 所代表的图像中以 cxcy(图像左上角为 0, 0)画一椭圆弧。如果成功则返回 TRUE,失败则返回 FALSE h 分别指定了椭圆的宽和高, e 参数以角度指定了起始和结束点。style 可以是下列值按位或(OR)后的值:

 IMG_ARC_PIE IMG_ARC_CHORD

 IMG_ARC_NOFILL IMG_ARC_EDGED

imagestring -- 水平地画一行字符串

语法:bool imagestring ( resource image,int font, int x, int y,string s, int col )

 imagestring()  col 颜色将字符串 s 画到 image 所代表的图像的 x坐标处(这是字符串左上角坐标,整幅图像的左上角为 00)。如果 font  123 5,则使用内置字体。

imagestringup -- 垂直地画一行字符串

语法:bool imagestringup ( resourceimage, int font, int x, inty, string s, int col )

 imagestring() col 颜色将字符串 s 垂直地画到 image 所代表的图像的 x , y 座标处(图像的左上角为 0, 0)。如果 font  123 5,则使用内置字体。

imagechar -- 水平地画一个字符

语法:bool imagechar ( resource image,int font, int x, int y, string c,int color )

 imagechar() 将字符串 c 的第一个字符画在 image 指定的图像中,其左上角位于 xy(图像左上角为 0, 0),颜色为color。如果 font 123 5,则使用内置的字体(更大的数字对应于更大的字体)。

imagecharup -- 垂直地画一个字符

语法:bool imagecharup ( resource image,int font, int x, int y, stringc, int color )

 imagecharup() 将字符 c 垂直地画在 image 指定的图像上,位于 xy(图像左上角为 0, 0),颜色为 color。如果 font  123 5,则使用内置的字体。

imagettftext --  TrueType 字体向图像写入文本

语法 array imagettftext ( resource image, floatsize, float angle, intx, int y, int color, string fontfile, string text )

代码:

         //1创建资源(画布的大小)

         $img = imagecreatetruecolor(200, 200);        

         //设置画布的颜色

         $white =  imagecolorallocate($img, 0xFF, 0xFF, 0xFF);

         $red = imagecolorallocate($img, 255, 0, 0);

         $blue = imagecolorallocate($img, 0, 0, 0XFF);

         $pink = imagecolorallocate($img, 0XFF, 0, 0XFF);

         $green =  imagecolorallocate($img, 0, 0xFF, 0);

        

         imagefill($img, 0, 0, $white);//填充画布颜色

         2、画各种图形    

         //画线

         imageline($img, 0,0, 200,200, $blue);

         imageline($img, 200, 0, 0, 200, $red);

 

         //画矩形

         imagerectangle($img, 50, 50, 150, 150,$pink);

         imagefilledrectangle($img, 75,75,125,125, $blue);

        

         //画圆

         imageellipse($img, 50, 50, 100, 100,$red);

         imagefilledellipse($img, 150, 150, 100,100, $red);

 

         //画弧形

         imagearc($img, 150, 50, 100, 100,  -90, 0, $blue);

 

         //画一个字符串

         imagestring($img, 5, 50, 150,"hello world", $blue);

         imagestringup($img, 5, 50, 150,"hello world", $blue);

 

         //3. 画出各种图形,和写(画出)

         imagettftext($img, 30, 0, 10, 100,$green, "./simkai.ttf", "妹子漂亮吗?");

         imagettftext($img, 30, 0, 13, 103,$red, "./simkai.ttf", "妹子漂亮吗?");

 

         //4保存,或输出给浏览写第二个参数就是保存

         header("Content-Type:images/gif");

 

         imagegif($img);

 

         //5. 释放资源

         imagedestroy($img);

 

4、时钟代码:

//获取系统时间

         date_default_timezone_set("PRC");

 

         $h = date("H");

         $i = date("i");

         $s = date("s");

 

         //1 创建资源(画布的大小)

         $img = imagecreatetruecolor(200, 250);        

         //设置画布的颜色

         $white =  imagecolorallocate($img, 0xFF, 0xFF, 0xFF);

         $red = imagecolorallocate($img, 255, 0, 0);

         $blue = imagecolorallocate($img, 0, 0, 0XFF);

         $pink = imagecolorallocate($img, 0XFF, 0, 0XFF);

         $green =  imagecolorallocate($img, 0, 0xFF, 0);

         imagefill($img, 0, 0, $white);

         //2. 制作各种图形

         imageellipse($img, 100, 100, 190, 190,$blue);

         imagefilledellipse($img, 100, 100, 4,4, $blue);

         imagestring($img, 3, 95, 8,  "12", $blue);

         imagestring($img, 3,180, 95,"03", $blue);

         imagestring($img, 3, 95, 180,  "06", $blue);

         imagestring($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;

 

         imageline($img, 100, 100, $x, $y,$red);

 

         //数字的时间

         imagestring($img, 5, 20, 230,"NOW: {$h}:{$i}:{$s}", $red);

 

         //4保存,或输出给浏览写第二个参数就是保存

         header("Content-Type:image/gif");

         imagegif($img);

 

         //5. 释放资源

         imagedestroy($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 =imagecreatetruecolor($this->width, $this->height);

//设置随机的背景颜色

$bgcolor =  imagecolorallocate($this->img, rand(225,255), rand(225, 255), rand(225, 255));

//设置背景填充

imagefill($this->img, 0, 0, $bgcolor);

//画边框

$bordercolor =  imagecolorallocate($this->img, 0, 0, 0);

imagerectangle($this->img, 0,0, $this->width-1, $this->height-1, $bordercolor);

                   }

                   //画字

privatefunction outstring() {

         for($i=0; $i<$this->num; $i++) {

         $color=imagecolorallocate($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,imagefontheight($fontsize)-3);

 

         //画出每个字符

                                     imagechar($this->img,$fontsize, $x, $y, $this->code{$i}, $color);

                            }

                   }

 

                   //设置干扰元素

privatefunction setdisturbcolor() {

         //加上点数

         for($i=0; $i<100; $i++) {

         $color=imagecolorallocate($this->img, rand(0, 255), rand(0, 255), rand(0, 255));

         imagesetpixel($this->img, rand(1,$this->width-2), rand(1, $this->height-2), $color);

                            }

         //加线条

for($i=0;$i<10; $i++) {

         $color=imagecolorallocate($this->img, rand(0, 255), rand(0, 128), rand(0, 255));

     imagearc($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 (imagetypes()& IMG_GIF) {

                                  header("Content-type: image/gif");

                                         imagegif($this->img);

                            } elseif(function_exists("imagejpeg")) {

                                  header("Content-type: image/jpeg");

                                  imagegif($this->img);

                            } elseif(imagetypes() & IMG_PNG) {

                                  header("Content-type: image/png");

                                         imagegif($this->img);

                            }  else {

                                     die("No image 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() {

                            imagedestroy($this->img);

                   }

 

         }

 

6Php图片处理

图片背景管理

图片缩放和裁剪

添加图片水印

图片旋转和翻转

 

图片背景管理

从指定的图片文件或 URL地址来新建一个图像。成功则返回一个图像标识符,失败时返回一个空字符串,并且输出一条错误信息。由于格式不同,则需要分别使用对应图片背景处理函数。

–resource imagecreatefrompng ( string filename )  PNG 文件或 URL 新建一图像

–resource imagecreatefromjpeg ( string filename )  JPEG 文件或 URL 新建一图像

–resource imagecreatefromgif ( string filename   GIF 文件或 URL 新建一图像

–resource imagecreatefromwbmp ( string filename )  WBMP 文件或 URL 新建一图像

 

其他图像处理函数:

– intimagesx ( resource image ) 取得图像宽度

– intimagesy ( resource image ) 取得图像高度

– arraygetimagesize ( string $filename [, array &$imageinfo ] ) 取得图像大小、类型等信息

代码:

<?php

         function cimgstr($imgname, $string) {

                   list($width, $height, $type)=getimagesize($imgname);

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   $img =$createimage($imgname);

                   $red =  imagecolorallocate($img, 0xFF, 0, 0);

                   $x =($width-imagefontwidth(5)*strlen($string))/2;

                   $y =($height-imagefontheight(5))/2;

                   imagestring($img, 5, $x, $y,$string, $red);

                   //变量函数

                   $save ="image".$types[$type];

                   $save($img,"new_".$imgname);

                   imagedestroy($img);

         }

         cimgstr("dx.jpg","meizi");

         cimgstr("map.gif","meizi");

         cimgstr("cx.png","meize");

 

7、图片的缩放和剪切

bool imagecopyresampled ( resource $dst_image , resource$src_image , 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_image  src_image 分别是目标图像和源图像的标识符。

缩放代码:

<?php

         function thumb($imgname, $width,$height) {

                   list($swidth, $sheight,$type)= getimagesize($imgname);

 

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   //$createimage =imagecreatefromipeg;

                   //原图片

                   $imgsrc =$createimage($imgname);

                   //目标资源

                   $dimg = imagecreatetruecolor($width,$height);

                  

                   imagecopyresampled($dimg,$imgsrc, 0, 0, 0, 0, $width, $height, $swidth, $sheight);

 

                   //变量函数

                   $save ="image".$types[$type];

                   $save($dimg,"new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($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)= getimagesize($imgname);

 

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   //原图片

                   $imgsrc =$createimage($imgname);

                   //目标资源

                   $dimg =imagecreatetruecolor($width, $height);

 

                   if ($width &&($swidth < $sheight)) {

                         $width = ($height / $sheight) * $swidth;

                   } else {

                       $height= ($width / $swidth) * $sheight;

                   }

 

                   imagecopyresampled($dimg,$imgsrc, 0, 0, 0, 0, $width, $height, $swidth, $sheight);

        

                   //变量函数

                   $save ="image".$types[$type];

                   $save($dimg,"new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($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)= getimagesize($imgname);

 

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   //原图片

                   $imgsrc =$createimage($imgname);

                   //目标资源

                   $dimg =imagecreatetruecolor($width, $height);

 

                   imagecopyresampled($dimg,$imgsrc, 0, 0, $x, $y, $width, $height, $width, $height);

                  

                   //变量函数

                   $save ="image".$types[$type];

                   $save($dimg,"new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($dimg);

         }

 

         cut("dx.jpg",50,50, 200,200);

         cut("map.gif",50,50, 200,200);

         cut("cx.png",50,50, 200,200);

 

8、添加图片水印

bool imagecopy( 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_xsrc_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x  dst_y 的位置上。

图片水印代码

<?php

         function watermark($imgname,$watername) {

                   list($swidth, $sheight,$type)= getimagesize($imgname);    //原图

                   list($wwidth, $wheight,$wtype)= getimagesize($watername);  //水印

 

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage = "imagecreatefrom".$types[$type];

                   $createimagew ="imagecreatefrom".$types[$wtype];

                   //原图片

                   $imgsrc =$createimage($imgname);   //原图

 

                   $wimg =$createimagew($watername);  //水印

 

                   $x = rand(3,$swidth-$wwidth);

                   $y = rand(3,$sheight-$wheight);

 

                   imagecopy($imgsrc, $wimg, $x,$y, 0, 0, $wwidth, $wheight);

                   //变量函数

                   $save ="image".$types[$type];

                   $save($imgsrc,"new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($wimg);

         }

         watermark("dx.jpg","php.gif");

         watermark("cx.png","php.gif");

文字水印代码:

<?php

         function watermark($imgname, $string) {

                   list($swidth, $sheight,$type)= getimagesize($imgname);

 

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   //原图片

                   $imgsrc = $createimage($imgname);

 

                   $white =imagecolorallocate($imgsrc, 200,200, 200);

                   $green =imagecolorallocate($imgsrc, 0,200, 0);

 

                   $x = rand(3,$swidth-strlen($string)*imagefontwidth(5));

                   $y = rand(3,$sheight-imagefontheight(5)-2);

 

                   imagestring($imgsrc, 5, $x, $y,$string, $white);

                   imagestring($imgsrc, 5, $x+1,$y+1, $string, $green);

                  

                   //变量函数

                   $save ="image".$types[$type];

                   $save($imgsrc,"new_".$imgname);

                   imagedestroy($imgsrc);

         //      imagedestroy($dimg);

         }

         watermark("dx.jpg","meizi");

         watermark("cx.png","meize");

 

9、图片旋转和翻转

resource imagerotate ( 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)= getimagesize($imgname);    //原图

        

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   $imgsrc =  $createimage($imgname);

        

                   //旋转

                   $new = imagerotate($imgsrc,$jd, 0);

 

                   //变量函数

                   $save ="image".$types[$type];

                   //保存

                   $save($new,"new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($new);

         }

         xz("php.gif", 90);

 

y轴旋转代码:

<?php

         //y轴翻转

         function trun_y($imgname) {

                   list($width, $height, $type)=getimagesize($imgname);    //原图

        

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   $imgsrc =  $createimage($imgname);

 

                   $new =imagecreatetruecolor($width, $height);   

                   //循环每次一个像素

                   for($x=0; $x<$width; $x++){

                            imagecopy($new,$imgsrc, $width-$x-1, 0, $x,0, 1, $height);        

                   }

 

                   //变量函数

                   $save ="image".$types[$type];

                   //保存

                   $save($new, "new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($new);

         }

         trun_y("cx.png");

x轴旋转代码:

<?php

         //x轴翻转

         function trun_x($imgname) {

                   list($width, $height, $type)=getimagesize($imgname);    //原图

        

                   $types =array(1=>"gif", 2=>"jpeg", 3=>"png");

 

                   //变量函数

                   $createimage ="imagecreatefrom".$types[$type];

                   $imgsrc =  $createimage($imgname);

 

                   $new =imagecreatetruecolor($width, $height);   

                   //循环每次一个像素

                   for($y=0; $y<$height;$y++) {

                            imagecopy($new,$imgsrc, 0, $height-$y-1, 0,$y, $width, 1);        

                   }

                  

                   //变量函数

                   $save ="image".$types[$type];

                   //保存

                   $save($new,"new_".$imgname);

                   imagedestroy($imgsrc);

                   imagedestroy($new);

         }

         trun_x("cx.png");

        

10、图像处理类

使用类代码:

<?php

         //包含这个类image.class.php

         include "image.class.php";

 

         $img = new Image("./images");

/*

         echo $img->thumb("dx.jpg",1000, 1000, "th1_")."<br>";

         echo $img->thumb("dx.jpg",800, 800, "th2_")."<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: image.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 = imagecreatetruecolor($width,$height);

/* 使用imagecopyresampled()函数对图片进行裁剪 */

imagecopyresampled($cutimg, $back,0, 0, $x, $y, $width, $height, $width, $height);

imagedestroy($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= getimagesize($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= imagecreatefromgif($srcPic);

                                               break;

                                     case2:                                           //jpg

                                               $img= imagecreatefromjpeg($srcPic);

                                               break;

                                     case3:                                           //png

                                               $img= imagecreatefrompng($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= imageGIF($newImg, $this->path.$newName);

                                               break;

                                     case2:                                 //jpg

                                               $result= imageJPEG($newImg,$this->path.$newName); 

                                               break;

                                     case3:                                 //png

                                               $result= imagePng($newImg, $this->path.$newName); 

                                               break;

                            }

                            imagedestroy($newImg);

                            return$newName;

                   }

 

                   /*内部使用的私有方法,用于加水印时复制图像 */

private function copyImage($groundImg,$waterImg, $pos, $waterInfo){

     imagecopy($groundImg,$waterImg, $pos["posX"], $pos["posY"], 0, 0,$waterInfo["width"],$waterInfo["height"]);

                            imagedestroy($waterImg);

                            return$groundImg;

                   }

 

/* 内部使用的私有方法,处理带有透明度的图片保持原样 */

                   privatefunction kidOfImage($srcImg, $size, $imgInfo){

                            $newImg= imagecreatetruecolor($size["width"], $size["height"]);              

                            $otsc= imagecolortransparent($srcImg);                                           

                            if($otsc >= 0 && $otsc < imagecolorstotal($srcImg)) {                 

                                    $transparentcolor = imagecolorsforindex($srcImg, $otsc );

                                     $newtransparentcolor = imagecolorallocate(

                                            $newImg,

                                             $transparentcolor['red'],

                                          $transparentcolor['green'],

                                            $transparentcolor['blue']

                                    );

                                    imagefill( $newImg, 0, 0, $newtransparentcolor);

                                    imagecolortransparent( $newImg,$newtransparentcolor );

                            }

imagecopyresized( $newImg, $srcImg, 0, 0, 0,0, $size["width"], $size["height"],$imgInfo["width"], $imgInfo["height"] );

                            imagedestroy($srcImg);

                            return$newImg;

                   }

         }

 

本文转自 sswqzx 51CTO博客,原文链接:http://blog.51cto.com/sswqzx/1969600



版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
centos下 Apache、php、mysql默认安装路径
apache: 如果采用RPM包安装,安装路径应在 /etc/httpd目录下 apache配置文件:/etc/httpd/conf/httpd.conf Apache模块路径:/usr/sbin/apachectl web目录:/var/www/html 如果采用源代码安装,一般默认安装在/usr/local/apache2目录下 php: 如果采用RPM包安装,安装路
3125 0
文章
问答
文章排行榜
最热
最新
相关电子书
更多
PHP与APM_技术内幕和最佳实践
立即下载
复杂PHP系统性能瓶颈排查及优化
立即下载
PHP安全开发_从白帽角度做安全
立即下载