新手,学php 没几天时间,写东西心里没根,也没写过类,今天花一天时间整合修改了一个,高手看看有什么问题测试 批量上传,缩略图 水印,没问题
<?php
class batchfileupload{

//文件数组
    public $uploadFiles=array();
    // 保存文件路径
    private $saveFilePath;
    //最大文件大小
    private $maxFileSize;
    //默认充许上传的文件类型
    private $allowType=array('gif','jpg','png','bmp');
 //mine类型
    private $allowMineType=array('image/pjpeg','image/gif');
//是否水印
private $ifwater;
//水印图片路径
private $watersrc;
//是否重命名
private $ifrename;
//是否生成缩略图
private $ifresize;
//缩略图标志
private $resizefileflag;
//生成缩略图的目标宽度
private $r_w;
//生成缩略图的目标高度
private $r_h;
    //上传成功的文件
    private $saveFileInfo = array();
    /*=====================================================
     * 构造函数,初始化:
     * @param array $file     文件域数组
     * @param string $path 文件保存路径
     * @param int $renameflag 是否重命名0 不命名,1重命名
     * @param int $waterflag 是否加水印0 不加,1加
 * @param string $ws 水印路径
 * @param array $type 允许上传的扩展名 数组
 * @param array $allowMineType 允许上传的mine类型    数组
 * @param int $resizeflag   是否生成缩略图 0不生成,1生成
 * @param string $resizefilenameflag   生成文件的文件名标志
     * @param int $overviewflag 是否覆盖0不覆盖 1覆盖
     * @param int $size 允许上传的最大字节数     =====================================================*/
public function __construct($file,$path,$renameflag=0,$overviewflag=0,$size=2000000,$type='',$allowMineType='',$resizeflag=0,$resizefilenameflag="_s",$r_w=500,$r_h=300,$waterflag=0,$ws='./images/w.gif')
{
$this->uploadFiles=$file;
$this->saveFilePath=$path;
$this->maxFileSize=$size;
$this->ifwater=$waterflag;
$this->watersrc=$ws;
$this->ifrename=$renameflag;
$this->ifoverview=$overviewflag;
$this->ifresize=$resizeflag;
$this->resizefileflag=$resizefilenameflag;
$this->r_w=$r_w;
$this->r_h=$r_h;
if($type !='') $this->allowType = $type;
if($allowMineType !='') $this->allowMineType = $allowMineType;
}
public function upload(){
$i=0;
foreach($this->uploadFiles as $file_arr){
if(!empty($file_arr['name'])){
$name=$file_arr['name'];
                $tmpname= $file_arr['tmp_name'];
                $size=$file_arr['size'];
                $minetype=$file_arr['type'];
$type=$this->getFileExt($name); //判断大小
if(!$this->checkSize($size)){
                    echo "文件大小超出限制.文件名称:".$name."<br>";
                    continue;
                }
//检查扩展名
                if(!$this->checkType($type)){
                 echo "非法的文件类型.文件名称:".$name."<br>";
                    continue;
                }
//检查mine
                if(!$this->checkType($minetype,0)){
                 echo "非法的mine类型.文件名称:".$name."<br>";
                    continue;
                }
//检测是否上传
                if(!is_uploaded_file($tmpname)){
                    echo "文件无效.文件名称:".$name."<br>";
                    continue;
                }
//建目录
@mkdir($this->saveFilePath);
                $y_path = $this->saveFilePath.date('Y');
                @mkdir($y_path);
                $final_path = $y_path.'/'.date('m').'/';
                @mkdir($final_path);
//获得文件名
//是否需要重命名
if($this->ifrename){
$final_file = time().mt_rand(1000,9999).'.'.$type;
}else{
$final_file=$name;
}
//判断是否覆盖
if(!$this->ifoverview && file_exists($final_path.$final_file)){
echo "文件已经存在.文件名称:<a target=blank href=$final_path$final_file>$final_path$final_file</a><br>";
                    continue;
}
move_uploaded_file($file_arr['tmp_name'],$final_path.$final_file);
//生成缩略图
if($this->ifresize){
if(!$this->resize($filename = $final_path.$final_file, $w = $this->r_w, $h = $this->r_h, $flag = "_s", $background = null, $color = '0xFFFFFF')){
echo "生成缩略图错误";
continue;
}
}
//加水印
if($this->ifwater){
$waterf=$this->imageWaterMark($final_path.$final_file,9,$this->watersrc);
if($waterf>0){
switch($waterf) {    //取得背景图片的格式  
 case 1:echo '水印图片格式目前不支持';break;
 case 2:echo '要水印的背景图片不存在';break;
 case 3:echo '需要加水印的图片的长度或宽度比水印图片或文字';break;
 case 4:echo '字体文件不存在';break;
 case 5:echo '水印文字颜色格式不正确';break;
 case 6:echo '水印背景图片格式目前不支持';break;
 default:echo '加水印遇到错误';break;
 }
 continue;
}
}
 //存储已经上传的文件信息
                $this->saveFileInfo[$i] = array(
                    'name'            => $name,
                    'type'            => $type,
                    'minetype'        => $minetype,
                    'size'                => $size,
                    'savename'    => $final_path.$final_file,
                    'path'            => $final_path.$final_file,
                );
$i++;
}
}
return $this->saveFileInfo;
}
//检查文件大小
private function checkSize($size){
        return $size>$this->maxFileSize?false:true;;
    }
//检查扩展名和mine
private function checkType($type,$flag=1){
if($flag==0){
foreach($this->allowMineType as $atype){
if(strcasecmp($type,$atype)==0) return true;
}
return false;
}else{
foreach($this->allowType as $atype){
if(strcasecmp($type,$atype)==0) return true;
}
return false;
}
    }

//获取文件扩展名
private function getFileExt($filename){
        $ext=pathinfo($filename);
        return $ext['extension'];
    }

解决方案 »

  1.   


    //加水印
     /*
    * 功能:PHP图片水印 (水印支持[zhi chi]图片或文字[wen zi])
    * 参数[can shu]:
    *       $groundImage     背景图片,即需要加水印的图片,暂只支持[zhi chi]GIF,JPG,PNG格式;
    *       $waterPos        水印位置[wei zhi],有10种状态[zhuang tai],0为随机位置[wei zhi];
    *                       1为顶端居左,2为顶端居中,3为顶端居右;
    *                       4为中部居左,5为中部居中,6为中部居右;
    *                       7为底端居左,8为底端居中,9为底端居右;
    *       $waterImage      图片水印,即作为水印的图片,暂只支持[zhi chi]GIF,JPG,PNG格式;
    *       $waterText       文字[wen zi]水印,即把文字[wen zi]作为为水印,支持[zhi chi]ASCII码,不支持[zhi chi]中文[zhong wen];
    *       $fontSize        文字[wen zi]大小,值为1、2、3、4或5,默认[mo ren]为5;
    *       $textColor       文字[wen zi]颜色,值为十六进制[shi liu jin zhi]颜色值,默认[mo ren]为#CCCCCC(白灰色);
    *       $fontfile        ttf字体[zi ti]文件[wen jian],即用来设置[she zhi]文字[wen zi]水印的字体[zi ti]。使用windows的用户[yong hu]在系统[xi tong]盘[xi tong pan]的目录中
    *                       搜索[sou suo]*.ttf可以得到系统[xi tong]中安装[an zhuang]的字体[zi ti]文件[wen jian],将所要的文件[wen jian]拷到网站[wang zhan]合适的目录中,
    *                       默认[mo ren]是当前目录[dang qian mu lu]下arial.ttf。
    *       $xOffset         水平偏移量[pian yi liang],即在默认[mo ren]水印坐标值基础上加上这个值,默认[mo ren]为0,如果你想留给水印留
    *                       出水平方向上的边距,可以设置[she zhi]这个值,如:2 则表示在默认[mo ren]的基础上向右移[you yi]2个单位[dan wei],-2 表示向左移[zuo yi]两单位[dan wei]
    *       $yOffset         垂直偏移量[pian yi liang],即在默认[mo ren]水印坐标值基础上加上这个值,默认[mo ren]为0,如果你想留给水印留
    *                       出垂直方向上的边距,可以设置[she zhi]这个值,如:2 则表示在默认[mo ren]的基础上向下移2个单位[dan wei],-2 表示向上移两单位[dan wei]
    * 返回值:
    *        0   水印成功
    *        1   水印图片格式目前不支持[zhi chi]
    *        2   要水印的背景图片不存在
    *        3   需要加水印的图片的长度或宽度比水印图片或文字[wen zi]区域[qu yu]还小,无法生成水印
    *        4   字体[zi ti]文件[wen jian]不存在
    *        5   水印文字[wen zi]颜色格式不正确
    *        6   水印背景图片格式目前不支持[zhi chi]
    * 修改[xiu gai]记录:
    *         
    * 注意:Support GD 2.0,Support FreeType、GIF Read、GIF Create、JPG 、PNG
    *       $waterImage 和 $waterText 最好不要同时使用,选其中之一即可,优先使用 $waterImage。
    *       当$waterImage有效[you xiao]时,参数[can shu]$waterString、$stringFont、$stringColor均不生效。
    *       加水印后的图片的文件[wen jian]名[wen jian ming]和 $groundImage 一样。
    * 作者:高西林
    * 日期:2007-4-28
    * 说明[shuo ming]:本程序根据longware的程序改写而成。
    */
    private function imageWaterMark($groundImage,$waterPos=0,$waterImage="",$waterText="",$fontSize=12,$textColor="#CCCCCC", $fontfile='./arial.ttf',$xOffset=0,$yOffset=0)
    {
       $isWaterImage = FALSE;
     //读取[du qu]水印文件[wen jian]
     if(!empty($waterImage) && file_exists($waterImage)) {
     $isWaterImage = TRUE;
     $water_info = getimagesize($waterImage);
     $water_w     = $water_info[0];//取得水印图片的宽
     $water_h     = $water_info[1];//取得水印图片的高
     switch($water_info[2])   {    //取得水印图片的格式  
     case 1:$water_im = imagecreatefromgif($waterImage);break;
     case 2:$water_im = imagecreatefromjpeg($waterImage);break;
     case 3:$water_im = imagecreatefrompng($waterImage);break;
     default:return 1;
     }
     }


     //读取[du qu]背景图片
     if(!empty($groundImage) && file_exists($groundImage)) {
     $ground_info = getimagesize($groundImage);
     $ground_w     = $ground_info[0];//取得背景图片的宽
     $ground_h     = $ground_info[1];//取得背景图片的高

     switch($ground_info[2]) {    //取得背景图片的格式  
     case 1:$ground_im = imagecreatefromgif($groundImage);break;
     case 2:$ground_im = imagecreatefromjpeg($groundImage);break;
     case 3:$ground_im = imagecreatefrompng($groundImage);break;
     default:return 1;
     }
     } else {
     return 2;
     }

     //水印位置[wei zhi]
     if($isWaterImage) { //图片水印  
     $w = $water_w;
     $h = $water_h;
     $label = "图片的";
     } else {  
     //文字[wen zi]水印
    if(!file_exists($fontfile))return 4;
     $temp = imagettfbbox($fontSize,0,$fontfile,$waterText);//取得使用 TrueType 字体[zi ti]的文本[wen ben]的范围[fan wei]
     $w = $temp[2] - $temp[6];
     $h = $temp[3] - $temp[7];
     unset($temp);
     }
     if( ($ground_w < $w) || ($ground_h < $h) ) {
     return 3;
     }
     switch($waterPos) {
     case 0://随机
     $posX = rand(0,($ground_w - $w));
     $posY = rand(0,($ground_h - $h));
     break;
     case 1://1为顶端居左
     $posX = 0;
     $posY = 0;
     break;
     case 2://2为顶端居中
     $posX = ($ground_w - $w) / 2;
     $posY = 0;
     break;
     case 3://3为顶端居右
     $posX = $ground_w - $w;
     $posY = 0;
     break;
     case 4://4为中部居左
     $posX = 0;
     $posY = ($ground_h - $h) / 2;
     break;
     case 5://5为中部居中
     $posX = ($ground_w - $w) / 2;
     $posY = ($ground_h - $h) / 2;
     break;
     case 6://6为中部居右
     $posX = $ground_w - $w;
     $posY = ($ground_h - $h) / 2;
     break;
     case 7://7为底端居左
     $posX = 0;
     $posY = $ground_h - $h;
     break;
     case 8://8为底端居中
     $posX = ($ground_w - $w) / 2;
     $posY = $ground_h - $h;
     break;
     case 9://9为底端居右
     $posX = $ground_w - $w;
     $posY = $ground_h - $h;
     break;
     default://随机
     $posX = rand(0,($ground_w - $w));
     $posY = rand(0,($ground_h - $h));
     break;     
     }

     //设定图像[tu xiang]的混色模式[mo shi]
     imagealphablending($ground_im, true);

     if($isWaterImage) { //图片水印
     imagecopy($ground_im, $water_im, $posX + $xOffset, $posY + $yOffset, 0, 0, $water_w,$water_h);//拷贝[kao bei]水印到目标[mu biao]文件[wen jian]         
     } else {//文字[wen zi]水印
     if( !empty($textColor) && (strlen($textColor)==7) ) {
     $R = hexdec(substr($textColor,1,2));
     $G = hexdec(substr($textColor,3,2));
     $B = hexdec(substr($textColor,5));
     } else {
       return 5;
     }
     imagettftext ( $ground_im, $fontSize, 0, $posX + $xOffset, $posY + $h + $yOffset, imagecolorallocate($ground_im, $R, $G, $B), $fontfile, $waterText);
     }

     //生成水印后的图片
     @unlink($groundImage);
     switch($ground_info[2]) {//取得背景图片的格式
     case 1:imagegif($ground_im,$groundImage);break;
     case 2:imagejpeg($ground_im,$groundImage);break;
     case 3:imagepng($ground_im,$groundImage);break;
     default: return 6;
     }

     //释放[shi fang]内存[nei cun]
     if(isset($water_info)) unset($water_info);
     if(isset($water_im)) imagedestroy($water_im);
     unset($ground_info);
     imagedestroy($ground_im);
     //
     return 0;
    }
    /**
     * 图片大小比例调整
     *
     * @param $filename       图片路径
     * @param $w              目标宽度
     * @param $h             目标高度
     * @param $flag       区别源文件的标志码
     * @param $background  是否产生背景, 如果要求产生背景则产生图像是指定的大小, 图片内容居中
     * @param $color            背景色
     */
    public function resize($filename = '', $w = 440, $h = 300, $flag = "_s" ,  $background = null, $color = '0xFFFFFF') {
    list ( $imgWidth, $imgHeight ) = getImageSize ( $filename );
    //如果原始宽高小于目标宽高,直接复制并改名
    if($imgWidth < $w && $imgHeight < $h){
    $temp_=pathinfo($filename);
    $mb_file=$temp_["dirname"]."/".str_replace(".", "$flag.", $temp_["basename"]);
    if(!copy($filename,$mb_file)){
    //echo("缩略图处理错误");
    return false;
    }
    return $mb_file;
    }
    $ratioX = $imgWidth / $w;
    $ratioY = $imgHeight / $h;

    if ($ratioX > $ratioY || $ratioX == $ratioY) {
    $dst_w = $w;
    $dst_h = ceil ( $imgHeight / $ratioX );
    } else if ($ratioY > $ratioX) {
    $dst_h = $h;
    $dst_w = ceil ( $imgWidth / $ratioY );
    }

    //判断图片类型
    $ext=strtolower ( strrchr ( $filename, '.' ) );
    switch ($ext) {
    case '.jpg' :
    case '.jpeg' :
    $im = imageCreateFromJpeg ( $filename );
    break;
    case '.gif' :
    $im = imageCreateFromGif ( $filename );
    break;

    case '.png' :
    $im = imageCreateFromPng ( $filename );
    }

    //是否有背景色
    if (null !== $background || $ext==".gif") {
    //将背景色转换为十进制的红绿蓝值
    $dec = hexdec ( $color );
    $red = 0xFF & ($dec >> 0x10);
    $green = 0xFF & ($dec >> 0x8);
    $blue = 0xFF & $dec;

    //居中定位并复制
    $dst_pos = array ('d_x' => 0, 'd_y' => 0 );
    ($dst_w == $w) ? ($dst_pos ['d_y'] = (($h - $dst_h) / 2)) : ($dst_pos ['d_x'] = (($w - $dst_w) / 2));

    $imBox = imageCreateTrueColor ( $w, $h );
    $color_bg = imageColorAllocate ( $imBox, $red, $green, $blue );
    imageFill ( $imBox, 0, 0, $color_bg );
    imageCopyResized ( $imBox, $im, $dst_pos ['d_x'], $dst_pos ['d_y'], 0, 0, $dst_w, $dst_h, $imgWidth, $imgHeight );
    } else {
    $imBox = imageCreateTrueColor ( $dst_w, $dst_h );
    imageCopyResized ( $imBox, $im, 0, 0, 0, 0, $dst_w, $dst_h, $imgWidth, $imgHeight );
    }

    $filename = str_replace ( strrchr ( $filename, '.' ), '', $filename ) . $flag.$ext;


    switch ($ext) {
    case '.jpg' :
    case '.jpeg' :
    return imagejpeg ( $imBox, $filename ) ? $filename : false;
    break;
    case '.gif' :
    return imagegif ( $imBox, $filename ) ? $filename : false;
    break;

    case '.png' :
    return imagepng ( $imBox, $filename ) ? $filename : false;
    }
    }
    }
    ?>