第八周周报

来源:互联网 发布:淘宝转化率0.05算正常 编辑:程序博客网 时间:2024/05/17 07:43

一.完善文件上传类(多个图片上传)

    1.1 name值一样的时候。

     1.2 name值不一样的时候

二.日期和时间函数

   2.1 与日期时间相关的函数 (6个)

2.2 用微妙统计文件执行时间

2.3 应用例子(日历程序)

三.制作缩略图

3.1 与缩略图相关的函数(14个同类8个)

3.2 把缩略图与水印封装到类

四.制作验证码

4.1 验证码的相关函数(12个)

4.2 把验证码封装到类

4.3 随机点名类

 

一.完善文件上传类(多个图片上传)

分两种情况:

1.1 文件的name属性不一样的时候:

     商品图片:<input type="file" name="pic1"/><br/>

 商品图片:<input type="file" name="pic2"/><br/>

 商品图片:<input type="file" name="pic3"/><br/>

   Php页面  $_FILES 会获得一个二维数组,表单元素每一个name值,对应一个元素(数组),

   思路: 我们要把一个二维数组数组遍历成一个一维的数组复制给一个变量后,在进行文件的判断上传。

foreach($_FILES as $file){

$upload->upload($file);

}

   1.2 表单元素的name属性一样的时候

 $_FILES 获得一个三维数组,只有一个元素:pic---->数组(5个元素)name、tmp_name、size、error 。我们知道 upload 这个方法,参数是一个一位数组:name、tmp_name、size、error。。。

接下来:

将这个三维数组,遍历成一个一维数组:

   代码如下:

 

for($i=0;$i<count($_FILES['pic']['name']);$i++){

$arr = array(

'name' => $_FILES['pic']['name'][$i],

'tmp_name' => $_FILES['pic']['tmp_name'][$i],

'type'=>  $_FILES['pic']['type'][$i],

'error'=>  $_FILES['pic']['error'][$i],

'size'=>  $_FILES['pic']['size'][$i]

);

$upload -> upload($arr);

}

总结:多文件上传无论name 值一样与否都要将多维数组遍历成一维数组,在进行判断上传。最重要的函数 move_uploade_files();

二.日期和时间函数

    2.1 与日期时间相关的函数

         Time() ----    返回当前的 Unix 时间戳,返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。

         Getdate()------获得日期和时间的函数

         Mktime()  -----将日期转换成UNIX时间戳

         Date() 将时间戳转换成 日期=格式年、月、日、时、分、秒、星期几

         Date_default_timezone_set()------设置时区:

         Microtime() ------返回当前UNIX时间戳 和 微秒数

 

 

Getdate()函数使用

Array getdate([ int $timestamp ] )

Mktime 的使用

Int mktime([int $hour[,int $minute[,int $second[,int $month[,int $day[,int $year[,int $is_dst]]]]]]])

     2.1 用微妙计算程序运行的时间

 

<?php

class Timer{

private $startTime;

private $stopTime;

 

function __construct(){

$this->startTime = 0;

$this->stopTime = 0;

}

public function getStart(){

$this->startTime = microtime(true);

}

public function getStop(){

$this->stopTime = microtime(true);

}

public function spent(){

return round($this->stopTime - $this->startTime,5);

}

}

 

<?php

require "Timer.class.php";

$timer = new Timer;

$timer->getStart();

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

}

$timer->getStop();

echo $timer->spent();

结果:

 

2.3 应用例子(日历程序---把日历程序封装到类)

   <?php

class Calendar{

private $year;//显示当前的年份

private $month;//显示当前的月份

private $day;//显示当前的日期

private $days;//显示当前月有多少天

private $start_weekday;//当前月第一天对应星期几

//初始化值

function __construct(){

$this->year = isset($_GET['year'])?$_GET['year']:date('Y');

$this->month = isset($_GET['month'])?$_GET['month']:date('m');

$this->day = date('d');

$this->days = date('t');

$this->start_weekday = date('w',mktime(0,0,0,date('m'),1,date('Y')));

}

 

 

public function show(){

echo '<table align="center">';

//日期的显示不能写死

$this -> changeDate();

$this -> weeklist();

$this->daylist();

echo '</table>';

}

//显示头部的星期列表

private function weeklist(){

$arr = array('日','一','二','三','四','五','六');

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

echo '<th>'.$arr[$i].'</th>';

}

}

//显示日期列表

private function daylist(){

//获得当前的月份

echo '<tr>';

for($j=1;$j<=$this->start_weekday;$j++){

echo '<td> </td>';

}

for($k=1;$k<=$this->days;$k++){

if($k==date('d')){

echo '<td class="week">'.$k.'</td>';

}else{

echo '<td>'.$k.'</td>';

}

if($j%7==0){

echo '</tr><tr>';

}

$j++;

}

echo '</tr>';

}

//获得上一年

private function prevYear($year,$month){

//月份保持不变  年份减一

//$year--;

//$year -= 1;

$year = $year -1;

if($year<1970){

$year = 1970;

}

return "year={$year}&month={$month}";

}

//获得上一个月

private function prevMonth($year,$month){

if($month==1){

$year = $year -1;

if($year <1970){

$year = 1970;

}

$month = 12;

}else{

$month = $month-1;

}

return "year={$year}&month={$month}";

}

//获得下一年

private function nextYear($year,$month){

$year += 1;

if($year>2038){

$year = 2038;

}

return "year={$year}&month={$month}";

}

//下一个月

private function nextMonth($year,$month){

if($month==12){

$year += 1;

if($year>2038){

$year = 2038;

}

$month = 1;

}else{

$month ++;

}

return "year={$year}&month={$month}";

}

 

//点击 <<  <  >  >> 分别显示对应的日期

private function changeDate(){

echo 'tr';

echo '<td><a href="?'.$this->prevYear($this->year,$this->month).'"><<</a></td>';

echo '<td><a href="?'.$this->prevMonth($this->year,$this->month).'"><</a></td>';

echo '<td colspan=3>'.$this->year.'-'.$this->month.'</td>';

echo '<td><a href="?'.$this->nextMonth($this->year,$this->month).'">></a></td>';

echo '<td><a href="?'.$this->nextYear($this->year,$this->month).'">>></a></td>';

echo '</tr>';

}

}

 

<style>

.week{

color:white;

background:blue;

}

</style>

<?php

require'calender.class.php';

$obj=new calender;

$obj->show();

 

三.制作缩略图

3.1 与缩略图相关的函数

Getimagesize()  -----  获得原图的信息

Imagecreatetruecolor()  获得目标图片资源  创建画布

    Imagecopyresampled()  将原图资源拷贝到目标资源上

     Imagejpeg()  输出或者保存图片

    Imagepng(resource $image[, string $filename [, int $quality ]] )      .  

    Imagegif()     .

Imagedestroy()   ---释放内存资源

 

注意:先获得原图资源时注意图片格式,用不同的函数;保存图片时也要注意图片格式用不同的函数,而且filename参数为可选,如果省略,则原始图像流将被直接输出。要省略 filename 参数而提供 quality 参数,使用空字符串('')。通过 header() 发送 Content-type: image/jpeg 可以使 PHP 脚本直接输出 JPEG 图像。 

 

 思路:根据原图资源在内存的画布中,创建一个图像;获得图片的信息,创建目标图片资源;在内存中创建目标图片的画布资;从原图资源上截取一部分,放到目标图片资源上;输出或者保存;最后,释放资源。

 

详细代码如下:

<?php

//提出疑问?

//长、宽  

//已知条件:1. 原图资源、2.目标图片资源、3.缩放的比率、 1600*1200 -----》  160*170

$src_filename = 'src.jpg';

//制作缩略图是在内存中进行转换的,思路:将原来的图片资源----内存的画布中,截取一部分,再将它按比率缩放之后保存到目标画布中,最后输出或者保存,销毁内存中的资源

//根据原图资源在内存的画布中,创建一个图像

$src_file = imagecreatefromjpeg($src_filename);

//print_r($src_Info);

//die();

$size = getimagesize($src_filename);//获得图片的信息

//原图的宽度、高度

$src_width = $size[0];

$src_height = $size[1];

 

//创建目标图片资源

$dst_width = 160;  

$dst_height = 120;

//在内存中创建目标图片的画布资源

$dst_file = imagecreatetruecolor($dst_width,$dst_height);

 

//从原图资源上截取一部分,放到目标图片资源上

//imagecopyresampled(目标图片资源、原来图片资源、目标图片左上角举行的x轴、目标图片左上角矩形y轴、原图左上角矩形的x轴、原图左上角矩形的y轴、目标图片资源的宽度、目标图片资源的高度、原图资源的宽度、原图资源的高度);

imagecopyresampled($dst_file,$src_file,0,0,0,0,$dst_width,$dst_height,$src_width,$src_height);

//输出或者保存

//header("Content-Type:image/jpeg");  //告诉浏览器给你返回的是图片

imagejpeg($dst_file,'dst.jpg');//保存什么格式的图片,如果只有一个参数,表示只是显示,如果提供第二个参数表示保存成一个文件

 

//最后,释放资源

imagedestroy($src_file);

imagedestroy($dst_file);

 

3.2 把缩略图封装到类

  <?php

class Image{

/***图像类包含(图像上传的方法、制作缩略图的方法、制作水印的方法)*/

/*图像上传方法

 * upload() 

 * 参数为数组,一位数组 5个元素 name type  size  tmp_name  error

public function upload($file){

if($file['error']==0){

//没有错误,已经上传到临时目录了

$allow_type = array('jpg','jpeg','png','gif');

$upload_name = $file['name'];

$arr = explode('.',$upload_name);

$upload_type = $arr[count($arr)-1];

if(in_array($upload_type,$allow_type)){

//图片类型符合要求

//判断大小

$maxsize= 200000;

if($file['size']<=$maxsize){

//大小也符合要求

//移动到指定目录中

$upload_path = './uploads/'.date('YmdHis').rand(100,999).strrchr($upload_name,'.');

if(is_uploaded_file($file['tmp_name'])){

if(move_uploaded_file($file['tmp_name'],$upload_path)){

return $upload_path;

}else{

echo '上传失败';

exit;

}

}

}else{

echo '文件太大了';

exit;

}

}else{

echo '格式不支持';

exit;

}

}else{

switch($file['error']){

case 1:

echo '上传的图片太大';

break;

case 2:

echo '超过了HTML表单中MAX_FILE_SIZE的最大值';

break;

case 3:

echo '文件只有部分被上传';

break;

case 4:

echo '没有文件被上传';

break;

case 6:

echo '找不到临时文件夹';

break;

default:

echo '未知错误';

}

exit;

}

}

/**缩略图方法 make_thumb()

 * @param  name文件名   width   height   prefix 新文件名(前缀 th_)

 * return 缩略图的文件名

 public function make_thumb($name,$max_width,$max_height){

//获得图像的信息

$imgInfo = $this -> getImgInfo($name);

//获得原图资源

$imgResorce = $this -> getSrcImg($name,$imgInfo);

//获得按照比例缩放的图片的大小

$dst = $this -> getNewImgSize($imgInfo,$max_width,$max_height); 

//获得目标图片资源

$dstResorce = $this -> getDstImg($imgResorce,$max_width,$max_height,$dst,$imgInfo);

//输出或者保存图片

$this -> saveNewImg($imgInfo,$dstResorce,$name);

 }

//获得图像信息

private function getImgInfo($name){

$data = getimagesize($name);

$imgInfo['width'] = $data[0];   //将图像的宽度 放到数组$imgInfo中,下标就是width

$imgInfo['height'] = $data[1];

$imgInfo['type'] = $data[2];

return $imgInfo;

}

//获得按照比例缩放之后的图像的大小

private function getNewImgSize($imgInfo,$max_width,$max_height){

//先定义缩略图宽度 和 高度

$dst['width'] = 0;

$dst['height'] = 0;

//原图的宽度 和 高度

$src_width = $imgInfo['width'];  

$src_height = $imgInfo['height'];

$src_scale = $src_width / $src_height;   

$max_scale = $max_width / $max_height;  

if($src_scale > $max_scale){

//先固定宽度

$dst['width'] = $max_width;

$dst['height'] = $dst['width'] / $src_scale;

}else{

$dst['height'] = $max_height;

$dst['width'] =  $dst['height'] * $src_scale;

}  

return $dst;

}

 private function getSrcImg($name,$imgInfo){

switch($imgInfo['type']){

case 1:

$imgresorce = imagecreatefromgif($name);

break;

case 2:

$imgresorce = imagecreatefromjpeg($name);

break;

case 3:

$imgresorce = imagecreatefrompng($name);

break;

}

return $imgresorce;

 }

 private function getDstImg($imgResorce,$max_width,$max_height,$dst,$imgInfo){

//创建画布  160   70   980 *1366

$dst_img = imagecreatetruecolor($dst['width'],$dst['height']);

//将原图资源拷贝到目标图片资源上

//注意:目标缩略图的大小不能写死

imagecopyresampled($dst_img,$imgResorce,0,0,0,0,$dst['width'],$dst['height'],$imgInfo['width'],$imgInfo['height']);

imagedestroy($imgResorce);//释放原图资源

return $dst_img;

 }

 private function saveNewImg($imgInfo,$dstResorce,$name){

//输出或者保存

$thumb_path = './uploads/'.date('YmdHis').rand(1000,9999).strrchr($name,'.');

if($dstResorce){

switch($imgInfo['type']){

case 1:

imagegif($dstResorce,$thumb_path);

break;

case 2:

imagejpeg($dstResorce,$thumb_path);

break;

case 3:

imagepng($dstResorce,$thumb_path);

break;

 }

}

imagedestroy($dstResorce);//释放目标缩略图的资源

return $thumb_path;

 }

/***制作水印

 * @param  $bgName    背景图

 * @param  $waterName 水印图

 * @param  $pos      位置

 *return 如果制作成功返回文件名,否则返回false

 public function waterMark($bgName,$waterName,$pos){

//获得图像信息

$bgImgInfo = $this -> getImgInfo($bgName);

$waterInfo = $this -> getImgInfo($waterName);

//获得背景图、水印图像的资源

$bgImgSrc = $this -> getSrcImg($bgName,$bgImgInfo);

$waterImgSrc = $this -> getSrcImg($waterName,$waterInfo);

//制作水印(需要确定水印的位置)

$pos = $this -> waterPos($bgImgInfo,$waterInfo,$pos);

var_dump($pos);

$this ->makeWater($bgImgSrc,$waterImgSrc,$pos,$waterInfo);

//输出或者保存

 }

 private function makeWater($bgImg,$waterImg,$pos,$waterInfo){

imagecopy($bgImg,$waterImg,$dst_x,$dst_y,0,0,$water_w,$water_h);

 }

 private function waterPos($bgImgInfo,$waterInfo,$pos){

//返回水印的位置

switch($pos){

case 1:

$dst_x = 0;

$dst_y = 0;

break;

case 2:

$dst_x = ($bgImgInfo['width']-$waterInfo['width'])/2;

$dst_y = 0;

break;

case 3:

$dst_x = $bgImgInfo['width']-$waterInfo['width'];

$dst_y = 0;

break;

case 4:

$dst_x = 0;

$dst_y = ($bgImgInfo['height']-$waterInfo['height'])/2;

break;

case 5:

$dst_x = ($bgImgInfo['width']-$waterInfo['width'])/2;

$dst_y = ($bgImgInfo['height']-$waterInfo['height'])/2;

break;

case 0:

default:

$dst_x = rand(0,$bgImgInfo['width']-$waterInfo['width']);

$dst_y = rand(0,$bgImgInfo['height']-$waterInfo['height']);

}

return array('x'=>$dst_x,'y'=>$dst_y);

 }

}

<?php

require 'Image.class.php';

$image = new Image;

$image -> watermark('src.jpg','water.jpg',3);

 

四.验证码的制作

       4.1 与验证码相关的函数

           绘制图形

           矩形:imagefilledrectangle(resource $imageint $x1 , int $y1 , int $x2 , int $y2 , int $color)

            Imagerectangle(resource $imageint $x1 , int $y1 , int $x2 , int $y2 , int $col) — 画一个矩形边框

           线段  imageline(resource $image, int $x1 , int $y1 , int $x2 , int $y2 , int $color

           点  imagesetpixel(resource $image, int $x , int $y , int $color)

           椭圆  bool imageellipseresource $image , int $cx , int $cy , int $w , int $h , int $color )

            画弧 bool imagefilledarc( resource $image , int $cx , int $cy , int $w , int $h , int $s , int $e , int $color , int $style )

        多边形bool  imagefilledpolygon( resource $image , array $points , int $num_points , int $color )

        在图像中绘制文字

        Imagestring()  水平的画一行字符串(从左向右)

            Imagestringup()  垂直的画一行字符串(从下向上)

            Imagechar()  水平的画一个字符

            Imagecharup()  垂直的画一个字符

           range('a','z');   //获得 从a-z之间的所有的单元

 

 

详细如下代码:

     <?php

$img = imagecreatetruecolor(200,200);

//分配颜色(画笔的颜色)

$white = imagecolorallocate($img,255,255,255);

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

$gray = imagecolorallocate($img,128,128,128);

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

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

//填充颜色

imagefilledrectangle($img,0,0,200,200,$white);

 

//绘制椭圆形

//imagefilledellipse($img,100,100,100,100,$gray);

//绘制扇形  弧度----设置扇形的开始和结束的角度  3点钟位置 0度   

//以顺时针运行

imagefilledarc($img,100,100,100,80,0,-140,$red,IMG_ARC_PIE);

imagefilledarc($img,100,100,100,80,-140,-90,$green,IMG_ARC_PIE);

imagefilledarc($img,100,100,100,80,-90,0,$blue,IMG_ARC_PIE);

 

//角度---从0度开始,以顺时针顺序运行

 

header('Content-Type:image/jpeg');

imagejpeg($img);

 

    4.2把验证码封装到类

        详细代码如下:

<?php

class Captcha{

private $width;//验证码的宽度

private $height;    //验证码的高度

private $strNum;    //验证码字符的数量

private $image;

private $disTurbNum;

public function __construct($width,$height,$strNum){

$this->width = $width;

$this->height = $height;

$this->strNum = $strNum;

$this-> disTurbNum = $this->width * $this->height/50; //密度

}

public function showImg(){

//创建矩形框(背景颜色)

$this->createBg();

//设置干扰元素(像素点、线条)

$this->setDisturb();

//输出文字到矩形框

$str = $this->outPutStr();

//输出\保存图像

$this->outPutImg();

return $str;

}

private function createBg(){

//创建画布

$this->image = imagecreatetruecolor($this->width,$this->height);

//分配画笔颜色

$bgColor =imagecolorallocate($this->image,mt_rand(50,255),mt_rand(50,255),mt_rand(50,255));

//填充颜色

imagefill($this->image,0,0,$bgColor);

//给背景创建一个边框

$borderColor = imagecolorallocate($this->image,0,0,0);

imagerectangle($this->image,0,0,$this->width-1,$this->height-1,$border);

}

//设置干扰元素

private function setDisturb(){

//像素点

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

$pxColor = imagecolorallocate($this->image,mt_rand(100,225),mt_rand(100,225),mt_rand(100,225));imagesetpixel($this->image,mt_rand(1,$this->width-2),mt_rand(1,$this->height-2),$pxColor);

}

//线条

for($j=0;$j<20;$j++){

$lineColor = imagecolorallocate($this->image,mt_rand(50,200),mt_rand(50,200),mt_rand(50,200));imageline($this->image,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$lineColor);

}

}

private function outPutStr(){

//a-z   A-Z   0-9

$lower_str = range('a','z');   //获得 从a-z之间的所有的单元

$upper_str = range('A','Z');//获得

$num = range(0,9);

//把这些数组合并

$new_all = array_merge($lower_str,$upper_str,$num);

$keys = array_rand($new_all,$this->strNum);

$str = '';

foreach($keys as $value){

$str .= $new_all[$value];

}

$strColor = imagecolorallocate($this->image,0,0,0);

imagestring($this->image,5,20,10,$str,$strColor);

//通常是保存到session

$_SESSION['captcha'] = $str; 

return $_SESSION['captcha'];

}

 

private function outPutImg(){

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

imagepng($this->image);

}

//销毁资源(析构方法----当类执行完毕会自动的调用这个方法)

private function __destruct(){

imagedestroy($this->image);

}

}

 

<?php

require 'Captcha.class.php';

$captcha = new Captcha(80,50,6);  //

$captcha -> showImg();//获得验证码的值

 

4.3 随机点名

详细代码如下:   

<?php

$name=file_get_contents('phpsum.txt');

//var_dump($name);

$sum=explode(',',$name);

$num=rand(0,count($sum)-1);

echo $sum[$num];

//echo $num;

//echo count($sum);

//exit;

array_splice($sum,$num,1);

$new_name=implode(',',$sum);

file_put_contents('phpsum.txt',$new_name);

 

 

原创粉丝点击