码迷,mamicode.com
首页 > Web开发 > 详细

PHP.15-图片处理类

时间:2016-11-28 22:39:48      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:locate   计算   高度   获取   private   return   存在   ota   case   

图片处理类

test.php

 1 <?php
 2 
 3     include "images.class.php";
 4     
 5     $image=new Image("./images/");    
 6     
 7     //对图片进行缩放
 8     
 9     echo $image->thumb("hee.jpg",300,300,"th1_");
10     echo $image->thumb("hee.jpg",200,200,"th2_");
11     echo $image->thumb("hee.jpg",100,100,"th3_");
12     
13     //对图片进行加水印
14     echo $image->waterMark("mag.gif","gaolf.gif",2,"wa2_");
15     echo $image->waterMark("mag.gif","gaolf.gif",6,"wa6_");
16     echo $image->waterMark("mag.gif","gaolf.gif",7,"wa7_");
17 ?>

 

images.class.php

  1 <?php
  2     class Image {
  3         private $path;
  4         
  5         //构造方法用来对图片所在位置进行初始化
  6         function __construct($path="./"){
  7             
  8             $this->path=rtrim($path,"/")."/";    //用户在输入路径时,无斜杠则加斜杠,有斜杠则删掉再加上
  9         }
 10         
 11         /*    功能:对图片进行缩放
 12         *    
 13         *    参数$name:需处理的图片名称
 14         *    参数$width:缩放后的宽度
 15         *    参数$height:缩放后的高度
 16         *    参数$qz:新图片的名称前缀
 17         *    返回值:缩放后的图片名称,失败返回false
 18         *
 19         */
 20         function thumb($name,$width,$height,$qz="th_"){
 21             //获取图片信息
 22             $imgInfo=$this->getInfo($name);    //原图片的信息
 23             
 24             //获取图片资源,通用各种类型的图片(png,jpg,gif)
 25             $srcImg=$this->getImg($name,$imgInfo);
 26             
 27             //获取计算图片等比例之后的大小
 28             $size=$this->getNewSize($name,$width,$height,$imgInfo);
 29             
 30             //获取新的图片资源,处理gif透明背景问题
 31             $newImg=$this->kid0fImage($srcImg,$size,$imgInfo);
 32             
 33             //另存为一个新的图片,返回新的缩放后的图片名称
 34             return $this->createNewImage($newImg,$qz.$name,$imgInfo);
 35         }
 36         
 37         
 38         private function createNewImage($newImg,$newName,$imgInfo){
 39             //另存图片
 40             switch($imgInfo["type"]){
 41                 case 1:                //gif
 42                         $result=imagegif($newImg,$this->path.$newName);
 43                         break;
 44                 case 2:                //jpg
 45                         $result=imagejpeg($newImg,$this->path.$newName);
 46                         break;
 47                 case 3:                //png
 48                         $result=imagepng($newImg,$this->path.$newName);
 49                         break;
 50             }
 51             imagedestroy($newImg);
 52             return $newName;
 53         }
 54         private function kid0fImage($srcImg,$size,$imgInfo){
 55             //创建新图片资源
 56             
 57             $newImg=imagecreatetruecolor($size["width"],$size["height"]);
 58             
 59             //取出透明色指数
 60             $otsc=imagecolortransparent($srcImg);
 61             
 62             //判断是否有透明色    //()取得一幅图像的调色板中颜色的数目
 63             if($otsc >=0 && $otsc <= imagecolorstotal($srcImg)){
 64                 $tran = imagecolorsforindex($srcImg,$otsc);    //取得某索引的颜色
 65                 
 66                 $newt = imagecolorallocate($newImg,$tran["red"],$tran["green"],$tran["blue"]);    //为一幅图片分配颜色
 67                 
 68                 imagefill($newImg,0,0,$newt);    //填充颜色
 69                 
 70                 imagecolortransparent($newImg,$newt);    //将某个颜色定义为透明色
 71             }
 72             //拷贝部分图像并调整大小
 73             imagecopyresized($newImg, $srcImg, 0, 0, 0, 0, $size["width"], $size["height"], $imgInfo["width"], $imgInfo["height"]);
 74             
 75             imagedestroy($srcImg);
 76             return $newImg;
 77         }
 78 
 79         private function getNewSize($name,$width,$height,$imgInfo){
 80             $size["width"]=$imgInfo["width"];
 81             $size["height"]=$imgInfo["height"];
 82             //如果缩放后宽度小于原图片宽度,再重新设置图片宽度
 83             if($width < $imgInfo["width"]){
 84                 $size["width"]=$width;
 85             }
 86             //如果缩放后高度小于原图高度,再重新设置图片高度
 87             if($height < $imgInfo["height"]){
 88                 $size["height"]=$height;
 89             }
 90             
 91             //图片等比例缩放的算法
 92             if($imgInfo["width"]*$width > $imgInfo["height"]*$height){
 93                 $size["height"]=round($imgInfo["height"]*$size["width"]/$imgInfo["width"]);
 94             }else{
 95                 $size["width"]=round($imgInfo["width"]*$size["height"]/$imgInfo["height"]);
 96             }
 97             
 98             return $size;
 99         }
100         private function getInfo($name){
101             $date=getImageSize($this->path.$name);
102             
103             $imageInfo["width"]=$date[0];
104             $imageInfo["height"]=$date[1];
105             $imageInfo["type"]=$date[2];
106             
107             return $imageInfo; 
108         }
109         private function getImg($name,$imgInfo){
110             $srcPic=$this->path.$name;        //某路径下的图片
111             
112             switch($imgInfo["type"]){
113                 case "1":        //gif
114                         $img=imagecreatefromgif($srcPic);
115                         break;
116                 case "2":        //jpg
117                         $img=imagecreatefromjpeg($srcPic);
118                         break;
119                 case "3":        //png
120                         $img=imagecreatefrompng($srcPic);
121                         break;
122                 default:
123                         return false;
124             }
125             return $img;
126         }
127         
128         
129         /*    功能:为图片加水印
130         *    
131         *    参数$groundName:背景图片,即需要加水印的图片
132         *    参数$waterMark:水印图片
133         *    参数$waterPos:水印位置,10种状态
134         *        0随机位置
135         *            1顶端居左    2顶端居中    3顶端居右
136         *            4中部居左    5中部居中    6中部居右
137         *            7底部居左    8底部居中    9底部居右
138         *
139         *    参数$qz:是加水印后图片名称的前缀
140         *    返回值:处理后图片的名称
141         */
142         function waterMark($groundName,$waterName,$waterPos=0,$qz="wa_"){
143             if(file_exists($this->path.$groundName) && file_exists($this->path.$waterName)){
144                 $groundInfo = $this->getInfo($groundName);
145                 $waterInfo = $this->getInfo($waterName);
146                 //水印位置
147                 if(!$pos = $this->position($groundInfo,$waterInfo,$waterPos)){
148                     echo "水印不应该比背景图片小";
149                     return;
150                 }
151                 $groundImg = $this->getImg($groundName,$groundInfo);
152                 $waterImg = $this->getImg($waterName, $waterInfo);
153                 
154                 $groundImg = $this->copyImage($groundImg, $waterImg, $pos, $waterInfo);
155                 return $this->createNewImage($groundImg, $qz.$groundName, $groundInfo);
156                 
157             }else{
158                 echo "图片或水印不存在";
159                 return false;
160             }
161         }
162         
163         private function copyImage($groundImg, $waterImg, $pos, $waterInfo){
164             imagecopy($groundImg, $waterImg, $pos["posX"], $pos["posY"], 0, 0, $waterInfo["width"], $waterInfo["height"]);
165             
166             imagedestroy($waterImg);
167             
168             return $groundImg;
169         }
170         private function position($groundInfo,$waterInfo,$waterPos){
171             //需要背景比水印图片大
172             if(($groundInfo["width"] < $waterInfo["width"]) || ($groundInfo["height"] < $waterInfo["height"])){
173                 return false;
174             }
175             switch($waterPos){
176                 case 1:            //顶部居左
177                         $posX=0;
178                         $posY=0;
179                         break;
180                 case 2:            //顶部居中
181                         $posX=($groundInfo["width"]-$waterInfo["width"])/2;
182                         $posY=0;
183                         break;
184                 case 3:            //顶部居右
185                         $posX=($groundInfo["width"]-$waterInfo["width"]);
186                         $posY=0;
187                         break;
188                 case 4:            //中部居左
189                         $posX=0;
190                         $posY=($groundInfo["height"]-$waterInfo["height"])/2;
191                         break;
192                 case 5:            //中部居中
193                         $posX=($groundInfo["width"]-$waterInfo["width"])/2;
194                         $posY=($groundInfo["height"]-$waterInfo["height"])/2;
195                         break;
196                 case 6:            //中部居右
197                         $posX=($groundInfo["width"]-$waterInfo["width"]);
198                         $posY=($groundInfo["height"]-$waterInfo["height"])/2;
199                         break;
200                 case 7:            //底部居左
201                         $posX=0;
202                         $posY=($groundInfo["height"]-$waterInfo["height"]);
203                         break;
204                 case 8:            //底部居中
205                         $posX=($groundInfo["width"]-$waterInfo["width"])/2;
206                         $posY=($groundInfo["height"]-$waterInfo["height"]);
207                         break;
208                 case 9:            //底部居右
209                         $posX=($groundInfo["width"]-$waterInfo["width"]);
210                         $posY=($groundInfo["height"]-$waterInfo["height"]);
211                         break;
212                 case 0:            //随机位置
213                         $posX=rand(0,($groundInfo["width"]-$waterInfo["width"]));
214                         $posY=rand(0,($groundInfo["height"]-$waterInfo["height"]));
215                         break;
216             }
217             return array("posX"=>$posX, "posY"=>$posY);
218         }
219     }
220 ?>

 

文件上传类

技术分享
  1 <?php
  2        /* 该用于文件上传
  3     * 有4个公有方法可以在对象外部调用:
  4     * __construct()构造方法用于初使化成员属性
  5     * uploadFile()方法用于上传文件
  6     * getNewFileName()方法用于获取上传成功后的文件名称
  7     * getErrorMsg()方法用于上传失败后获取错误提示信息
  8     * 其它属性和方法都被本类封装,不可以在对象外部调用
  9     */
 10     class FileUpload {    
 11         private $filepath;     // 上传文件的目的路径
 12         private $allowtype = array(‘jpg‘,‘gif‘,‘png‘); //充许上传文件的类型,使用小字母
 13         private $maxsize = 1000000;  //允许文件上传的最大长度1m
 14         private $israndname = true;   //是否随机重命名 false为不随机
 15         private $originName;     //源文件名
 16         private $tmpFileName;   //临时文件名
 17         private $fileType;     //文件类型(文件后缀)
 18         private $fileSize;     //文件大小
 19         private $newFileName;     //新文件名
 20         private $errorNum = 0; //错误号
 21         private $errorMess="";  //错误报告消息
 22         /* 构造方法:为成员属性初使化
 23          * 参数$options:为一个数组,数组下标为成员员属性名称字符串
 24          * 本类需要初使化的属性有 filepath, allowtype, maxsize,israndname四个属性,其中filepath为必须设置的属性
 25          * 使用的格式为 new FileUpload(array(‘filepath‘=>‘./uploads‘, ‘maxsize‘=>10000000)) 的格式
 26          */
 27         function __construct($options=array()) {
 28             foreach ($options as $key=>$val) {
 29                 $key=strtolower($key);   //在为成员属性设置值时,不区分大小写
 30                 if (!in_array($key,get_class_vars(get_class($this)))) 
 31                     continue;
 32                 $this->setOption($key, $val);
 33             }
 34         }
 35 
 36         /* 调用该方法上传文件
 37          * 参数: 上传文件的表单名称 例如:<input type="file" name="myfile"> 参数则为myfile
 38          * 返回值: 如果上传成功返回数字0,如果上传失败则返回小于0的数,如:-1、-2、-3、-4、-5中的一个 
 39          */
 40         
 41         function uploadFile($fileField) {
 42             $return=true;
 43             if(!$this->checkFilePath()) {//检查文件路径
 44                 $this->errorMess=$this->getError();
 45                 return false;
 46             }
 47             $name=$_FILES[$fileField][‘name‘];
 48             $tmp_name=$_FILES[$fileField][‘tmp_name‘];
 49             $size=$_FILES[$fileField][‘size‘];
 50             $error=$_FILES[$fileField][‘error‘];
 51 
 52         
 53         
 54             if(is_Array($name)){  //如果是多个文件上传则$file["name"]会是一个数组
 55                 $errors=array();
 56                 for($i = 0; $i < count($name); $i++){ 
 57                     if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {//设置文件信息
 58                         if(!$this->checkFileSize() || !$this->checkFileType()){
 59                             $errors[]=$this->getError();
 60                             $return=false;    
 61                         }
 62                     }else{
 63                         $errors[]=$this->getError();
 64                         $return=false;
 65                     }
 66 
 67                     if(!$return)  // 如果有问题,则重新初使化属性
 68                         $this->setFiles();
 69                 }
 70             
 71                 if($return){
 72                     $fileNames=array();   //存放所有上传后文件名的变量数组
 73         
 74                     for($i = 0; $i < count($name);  $i++){ 
 75                         if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {//设置文件信息
 76                             $this->setNewFileName(); //设置新文件名
 77                             if(!$this->copyFile()){
 78                                 $errors[]=$this->getError();
 79                                 $return=false;
 80                             }
 81                             $fileNames[]=$this->newFileName;
 82                         }
 83                                             
 84                     }
 85                     $this->newFileName=$fileNames;
 86                     
 87                 }
 88                 $this->errorMess=$errors;
 89                 return $return;
 90                 
 91             } else {
 92                 if($this->setFiles($name,$tmp_name,$size,$error)) {//设置文件信息
 93                     if($this->checkFileSize() && $this->checkFileType()){    
 94                         $this->setNewFileName(); //设置新文件名
 95                         if($this->copyFile()){ //上传文件   返回0为成功, 小于0都为错误
 96                             return true;
 97                         }else{
 98                             echo ‘3333333333333‘;
 99                             $return=false;
100                         }
101                     }else{
102                         $return=false;
103                     }
104                 } else {
105                     $return=false;    
106                 }
107 
108                 if(!$return)
109                     $this->errorMess=$this->getError();
110 
111                 return $return;
112             }
113         
114         }
115 
116         /* 获取上传后的文件名称
117          * 没有参数
118          * 返回值:上传后,新文件的名称
119          */
120         public function getNewFileName(){
121             return $this->newFileName;
122         }
123 
124         public function getErrorMsg(){
125             return $this->errorMess;
126         }
127         
128         /* 上传失败后,调用该方法则返回,上传出错信息
129          * 没有参数
130          * 返回值:返回上传文件出错的信息提示
131          */
132         private function getError() {
133             $str = "上传文件<font color=‘red‘>{$this->originName}</font>时出错 : ";
134             switch ($this->errorNum) {
135                 case 4: $str .= "没有文件被上传"; break;
136                 case 3: $str .= "文件只有部分被上传"; break;
137                 case 2: $str .= "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值"; break;
138                 case 1: $str .= "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值"; break;
139                 case -1: $str .= "未允许类型"; break;
140                 case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break;
141                 case -3: $str .= "上传失败"; break;
142                 case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
143                 case -5: $str .= "必须指定上传文件的路径"; break;
144                 default: $str .= "未知错误";
145             }
146             return $str.‘<br>‘;
147         }
148 
149         
150         //设置和$_FILES有关的内容
151         private function setFiles($name="", $tmp_name="", $size=0, $error=0) {
152             $this->setOption(‘errorNum‘, $error);
153             if($error)
154                 return false;
155             $this->setOption(‘originName‘, $name);
156             $this->setOption(‘tmpFileName‘,$tmp_name);
157             $aryStr = explode(".", $name);
158             $this->setOption(‘fileType‘, strtolower($aryStr[count($aryStr)-1]));
159             $this->setOption(‘fileSize‘, $size);
160             return true;
161         }
162     
163         //为单个成员属性设置值
164         private function setOption($key, $val) {
165             $this->$key = $val;
166         }
167 
168         //设置上传后的文件名称
169         private function setNewFileName() {
170             if ($this->israndname) {
171                 $this->setOption(‘newFileName‘, $this->proRandName());    
172             } else{ 
173                 $this->setOption(‘newFileName‘, $this->originName);
174             } 
175         }
176          
177         //检查上传的文件是否是合法的类型
178         private function checkFileType() {
179             if (in_array(strtolower($this->fileType), $this->allowtype)) {
180                 return true;
181             }else {
182                 $this->setOption(‘errorNum‘, -1);
183                 return false;
184             }
185         }
186             //检查上传的文件是否是允许的大小
187         private function checkFileSize() {
188             if ($this->fileSize > $this->maxsize) {
189                 $this->setOption(‘errorNum‘, -2);
190                 return false;
191             }else{
192                 return true;
193             }
194         }
195 
196         //检查是否有存放上传文件的目录
197         private function checkFilePath() {
198             if(empty($this->filepath)){
199                 $this->setOption(‘errorNum‘, -5);
200                 return false;
201             }
202             if (!file_exists($this->filepath) || !is_writable($this->filepath)) {
203                 if (!@mkdir($this->filepath, 0755)) {
204                     $this->setOption(‘errorNum‘, -4);
205                     return false;
206                 }
207             }
208 
209             return true;
210         }
211         //设置随机文件名
212         private function proRandName() {        
213             $fileName=date(‘YmdHis‘)."_".rand(100,999);   //获取随机文件名    
214             return $fileName.‘.‘.$this->fileType;    //返回文件名加原扩展名
215         }
216         
217 
218         //复制上传文件到指定的位置
219         private function copyFile() {
220             if(!$this->errorNum) {
221                 $filepath = rtrim($this->filepath, ‘/‘).‘/‘;
222                 $filepath .= $this->newFileName;
223                 if (@move_uploaded_file($this->tmpFileName, $filepath)) {
224                     return true;
225                 }else{
226                     $this->setOption(‘errorNum‘, -3);
227                     return false;
228                 }
229             } else {
230                 return false;
231             }
232         
233         }
234         
235     }
FileClass

 

技术分享
 1 <?php
 2         include "FileUpload.class.php";
 3         include "images.class.php";
 4         
 5         $up = new FileUpload(array("filepath" => "./images/", "allowtype" => array("gif", "jpg","png")));
 6         
 7         if($up->uploadFile("spic")){
 8             $filename = $up->getNewFileName();
 9             
10             $img = new Image("./images");
11             
12             $th_filename = $img->thumb($filename, 300,300, "th_");
13             
14             $img->waterMark($th_filename, "gaolf/gif", 5, "wa_");
15             $img->waterMark($filename, "gaolf.gif", 0, "");
16         }else{
17             echo $up->getErrorMsg();
18         }
19 ?>
upload

 

PHP.15-图片处理类

标签:locate   计算   高度   获取   private   return   存在   ota   case   

原文地址:http://www.cnblogs.com/zixuanfy/p/6111518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!