PHP系列(十)GD庫

科技小能手發表於2017-11-12

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); //建立畫布的大小為100×100

$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


相關文章