1、php在使用GD庫的時候應打開對應的GD庫擴展,如下圖
2、GD庫的開頭小案例
imagecreatetruecolor(width, height) 創建一個幕布
imagecolorallocate(handle, red, green, blue) 定義一個顏色
imagecolortransparent(handle, color) 把顏色設置為透明顏色, 第二個參數為imagecolorallocate對象的顏色
imagefill(handle, x, y, color) 填充幕布的顏色
1 <?php 2 header('content-type:image/png'); 3 ini_set('display_errors', true); 4 //創建畫布,並且指定寬高 5 $handle = imagecreatetruecolor(300, 200); 6 //給畫布創建顏色 7 $bgColor = imagecolorallocate($handle, 200,15,16); 8 //把顏色從(0,0)點開始填充到畫布 9 imagefill($handle, 0,0, $bgColor); 10 //繪制直線 11 $lineColor = imagecolorallocate($handle, 200,200,200); 12 //參數二表示起點的x軸坐標 13 //參數三表示起點的Y軸坐標 14 //參數四表示終點的x軸坐標 15 //參數五表示終點的Y軸坐標 16 imageline($handle, 0,0,100,200, $lineColor); 17 //輸出 18 imagepng($handle); 19 //銷毀圖像 20 imagedestroy($handle); 21 ?>
3、使用GD庫繪制矩形
<?php header('content-type:image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(300, 200); $bgColor = imagecolorallocate($handle, 50, 150, 250); imagefill($handle, 0, 0, $bgColor); $rectColor = imagecolorallocate($handle, 232, 16, 16); //繪制一個描邊的矩形 //第二個參數表示 imagerectangle($handle, 50, 50, 150, 150, $rectColor); //繪制一個填充的矩形 imagefilledrectangle($handle, 180, 50, 280, 150, $rectColor); imagepng($handle); imagedestroy($handle); ?>
4、使用GD庫繪制圓形
<?php header('content-type:image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(400, 200); $bgColor = imagecolorallocate($handle, 200,20,50); imagefill($handle, 0, 0, $bgColor); $color = imagecolorallocate($handle, 132, 209, 73); //繪制邊軭的圓 imageellipse($handle, 100,100, 100, 100, $color); //繪制填充的圓 imagefilledellipse($handle, 300, 100, 100 ,100, $color); imagepng($handle); imagedestroy($handle); ?>
5、使用圖片的復制功能
imagesx($handle) 可以獲取圖片的寬度
imagesy($handle) 可以獲取圖片的高度
getimagesize($filename) 可以獲取圖片的大小,類型等相關的信息
imagecopyresampled($dsimage, $srcimage, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); 復制圖片並且調整大小
<?php header('content-type:image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(400, 200); $bgColor = imagecolorallocate($handle, 255, 255, 153); imagefill($handle, 0, 0, $bgColor); //獲取需要復制的原圖 $source = imagecreatefrompng('test.png'); //獲取原圖的寬 $imagex = imagesx($source); //獲取原圖的高 $imagey = imagesy($source); //執行圖片的復制 //參數1表示目標圖片 //參數2表示原圖資源 //參數3,4表示目標圖片起始x,y點 //參數5,6表示原圖圖片的起始x,y點 //參數7,8表示圖片的寬高 imagecopy($handle, $source, 0, 0, 0, 0, $imagex, $imagey); imagepng($handle); imagedestroy($handle); ?>
6、GD庫繪制字符串與文字
imagestring => 不能指定繪制的字體
imagettftext => 可以指定繪制的字體
imagepng($handle, $newFileName) 當沒有newFileName的時候會以圖片的形式輸出,當有第二個參數時,會保存到指定的文件里
imagegif,imagejpeg的用法如上
<?php header('content-type:image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(400, 200); $bgColor = imagecolorallocate($handle, 255, 200, 10); imagefill($handle, 0, 0, $bgColor); $fontColor = imagecolorallocate($handle, 0, 0, 160); //繪制字體 //參數二表示,字體的大小,但是似乎沒有多大的用處 //參數三和參數四表示,字體開始的起點的x軸和Y軸坐標 //參數五表示,需要繪制的內容 //參數六表示,字體的顏色 //注意,因為這個函數不能指定字體以及更多的屬性,因此更多的是使用imagettftext這個函數 imagestring($handle, 100, 10, 10, 'are you ok???',$fontColor); imagepng($handle); imagedestroy($handle); ?>
<?php header('content-type: image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(400, 200); $bgColor = imagecolorallocate($handle, 200, 230, 20); imagefill($handle, 0, 0, $bgColor); $fontColor = imagecolorallocate($handle, 200, 0, 200); //參數二:表示字體的大小 //參數三:表示字體的旋轉角度 //參數四:表示起始的X軸起點 //參數五:表示起始的Y軸起點 //參數六:表示字體的顏色 //參數七:表示字體文件的路徑 //參數八:表示渲染的內容 imagettftext($handle, 30, 20, 100, 150, $fontColor, './resource/STHUPO.TTF', 'hello world'); imagepng($handle); imagedestroy($handle); ?>
7、GD庫繪制弧形
<?php header('content-type:image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(400, 200); $bgColor = imagecolorallocate($handle, 200, 200, 10); imagefill($handle, 0, 0, $bgColor); $lineColor = imagecolorallocate($handle, 255, 0, 255); //參數二,三:表示圓心的X軸坐標,Y軸坐標 //參數四,五:表示弧度的寬和高 //參數六,七:表示弧度的起點和終點,(起點表示三點鍾方向) //參數八:表示線條的顏色 imagearc($handle, 100, 100, 100, 100, 0, 180, $lineColor); //其他參數和上面的函數一樣,最后一個參數表示類型,也可以用0表示 imagefilledarc($handle, 300, 100, 100,100, 90, 270, $lineColor,IMG_ARC_PIE); imagepng($handle); imagedestroy($handle); ?>
8、用GD庫繪制點
<?php header('content-type: image/png'); ini_set('display_errors', true); $handle = imagecreatetruecolor(400, 200); $bgColor = imagecolorallocate($handle, 200, 200, 150); imagefill($handle, 0, 0, $bgColor); for ($i = 0; $i < 10000; $i++) { $dotColor = imagecolorallocate($handle, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //創建點 //第二個參數和第三個參數分別表示點的x軸和y軸坐標 //參數四表示點的顏色 imagesetpixel($handle, mt_rand(0, 400), mt_rand(0, 200), $dotColor); } imagepng($handle); imagedestroy($handle); ?>
9、封裝生成驗證碼的類
<?php ini_set('display_errors', true); class Captcha { private $config = [ 'width' => 100, //畫布的寬 'height' => 30, //畫布的高 'number' => 4, //生成隨機數的數量 'font' => './resource/STHUPO.TTF', //驗證碼的字體 'fontSize' => 18, //字體大小 'content' => [] ]; private $handle; //驗證碼句柄 public function __construct(array $conf = []) { $this->config = array_replace($this->config, $conf); empty($this->config['content'])? $this->config['content'] = $this->fillText(): null; //如果沒有內容,那么要創造內容 } public function init() { header('content-type: image/png'); $this->createPng(); $this->createText(); $this->createDot(); $this->createLine(); imagepng($this->handle); imagedestroy($this->handle); } /**創建文字 * @return array */ private function fillText() { return $content = array_merge(range('a', 'z'), range('A', 'Z'), range(3,9)); } /** * 創建幕布 */ private function createPng() { $this->handle = imagecreatetruecolor($this->config['width'], $this->config['height']); $bgColor = imagecolorallocate($this->handle, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200)); imagefill($this->handle, 0, 0, $bgColor); } /** * 創建字體 */ private function createText() { $space = $this->config['width'] / (1+$this->config['number']); for($i = 0; $i < $this->config['number']; $i ++) { $fontColor = imagecolorallocate($this->handle, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100)); $text = $this->config['content'][mt_rand(0, count($this->config['content'])-1)]; $height = ($this->config['height'] + $this->config['fontSize']) / 2; $width = ($i+1) * $space - $this->config['fontSize'] /2; imagettftext($this->handle, $this->config['fontSize'], mt_rand(-30, 30), $width, $height, $fontColor, $this->config['font'], $text); } } /** * 畫干擾點 */ private function createDot() { for($i = 0; $i < 100; $i ++) { $dotColor = imagecolorallocate($this->handle, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($this->handle, mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), $dotColor); } } /** * 繪制曲直干擾線 */ private function createLine() { for($i = 0; $i < 5; $i ++) { $lineColor = imagecolorallocate($this->handle, mt_rand(0,100), mt_rand(0, 100), mt_rand(0, 100)); imageline($this->handle, mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), $lineColor); imagearc($this->handle, mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), mt_rand(0, 360), mt_rand(0, 360), $lineColor); } } } $c = new Captcha([ 'content'=> ['你','我','他', '是', '給'], // 'fontSize' => 12, ]); $c->init(); ?>
10、在上傳圖片上添加水印的類(PHP部份)
<?php header('content-type:text/html;charset=utf-8'); ini_set('display_errors', true); class UploadFile { private $file; private $allowType = ['image/png', 'image/jpg', 'image/jpeg']; private $limitSize = 3*1024*1024; private $targetPath = 'd:/uploadFile'; public function __construct() { if($_FILES['file']['error'] === 4) { die('請上傳文件'); } $this->file = $_FILES['file']; } private function getExtension() { return substr(strrchr($this->file['name'], '.'), 1); } private function getNewFile() { $file = sprintf('%s/%s',$this->targetPath, date('Ymd')); if(!file_exists($file)) { mkdir($file, 0777, true); } return $file; } private function getNewFileName() { return sprintf('%s/%s.%s', $this->getNewFile(), uniqid('up_', true),$this->getExtension()); } private function checkFileType() { $finfo = new finfo(FILEINFO_MIME_TYPE); $type =$finfo->file($this->file['tmp_name']); return in_array($type, $this->allowType) && in_array($this->file['type'], $this->allowType); } private function checkFileSize() { return $this->file['size'] <= $this->limitSize; } /**實現圖片的水印 * @param $file * @param $newFileName * @return bool */ private function printLogo($file, $newFileName) { $ext = $this->getExtension(); $handle = null; switch(strtolower($ext)) { case 'jpg' || 'jpeg': $handle = imagecreatefromjpeg($file);break; case 'png': $handle = imagecreatefrompng($file);break; } $fontColor = imagecolorallocate($handle, 0, 0, 0); imagettftext($handle, 40,-30, 100, 100, $fontColor,'./resource/STHUPO.TTF', 'are you ok???'); $res = imagejpeg($handle, $newFileName); imagedestroy($handle); return $res; } public function init() { if(is_uploaded_file($this->file['tmp_name'])) { !$this->checkFileType() ? die(sprintf('上傳的類型錯誤,只允許上傳%s類型的文件', implode(',', $this->allowType))): null; !$this->checkFileSize() ? die(sprintf('上傳的大小錯誤,只允許上傳%d大小的文件', $this->limitSize)): null; $fileName = $this->getNewFileName(); if($this->printLogo($this->file['tmp_name'], $fileName)) { echo '上傳成功'; } else { echo '上傳失敗'; } } else { echo 'unknow'; } } } $u = new UploadFile(); $u->init(); ?>
html部份
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>test</title> </head> <body> <form action="./test.php" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="提交"> </form> </body> </html>
11、圖像的壓縮
介紹:在圖像上傳后,一般不直接使用圖片,因為圖片往往過大,一般通過等比例壓縮后再使用
<?php header('content-type:text/html; charset=utf-8'); ini_set('display_errors', true); class ThumbPress{ private $handle; //原圖的句柄 private $type; //文件類型 private $src_width; //原圖的寬 private $src_height; //原圖的高 private $limitType = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']; private $imageCreate = ['imagecreatefrompng', 'imagecreatefromjpeg', 'imagecreatefromjpeg', 'imagecreatefromgif']; private $imageOutPut = ['imagepng', 'imagejpeg', 'imagejpeg', 'imagegif']; private $config = [ 'width' => 50, 'height' => 50, 'text' => '', 'fontSize' => 20, 'font' => './resource/STHUPO.TTF', 'targetFile' => 'd:/uploadFile/thumbImg' ]; public function __construct($conf) { $this->config = array_replace($this->config, $conf); if(file_exists($this->config['filename']) && in_array($this->type = mime_content_type($this->config['filename']), $this->limitType)) { $this->handle = array_combine($this->limitType, $this->imageCreate)[$this->type]($this->config['filename']); } } /**計算縮放比率 * @return float|int */ private function getScaleBite() { $scale = 1; $this->src_width = imagesx($this->handle); $this->src_height = imagesy($this->handle); switch(true) { case $this->src_width >= $this->src_height: $scale = $this->src_width / $this->config['width']; break; case $this->src_width < $this->src_height: $scale = $this->src_height / $this->config['hegiht']; break; } return $scale; } /**創建新圖片的幕布 * @return false|resource */ private function createScreen() { $screen = imagecreatetruecolor($this->config['width'], $this->config['height']); $color = imagecolorallocate($screen, 255, 255, 255); $color = imagecolortransparent($screen, $color); imagefill($screen, 0, 0, $color); return $screen; } /**創建圖片新名字,生成新地址 * @return string */ private function createFilePath(): string { $name = sprintf('thumb_%s', basename($this->config['filename'])); if(!file_exists($this->config['targetFile'])) { mkdir($this->config['targetFile'], 0777, true); } return sprintf('%s/%s', $this->config['targetFile'], $name); } /**打印水印 * @param $screen */ private function printLogo($screen) { if(!$this->config['text']) { return; } $fontColor = imagecolorallocate($screen, 0, 0, 0); imagettftext($screen, $this->config['fontSize'], 0, 20, 20, $fontColor, $this->config['font'], $this->config['text']); } /**壓縮圖片 * @return string */ private function imageThumb(): string { $screen = $this->createScreen(); $scale = $this->getScaleBite(); $newFileName = $this->createFilePath(); $targetWidth = $this->src_width / $scale; $targetHeight = $this->src_height / $scale; imagecopyresampled($screen, $this->handle,0,0,0,0, $targetWidth, $targetHeight, $this->src_width, $this->src_height); $this->printLogo($screen); array_combine($this->limitType, $this->imageOutPut)[$this->type]($screen, $newFileName); //輸出圖片 return $newFileName; //返回新圖片的名字 } public function init() { if(!$this->handle) { return false; } return $this->imageThumb(); } } ?>