php实现文件在线压缩功能
<?php
class ZipAllFloder{
var $cachelist = array();
var $datasec = array();
var $ctrl_dir = array();
var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
var $old_offset = 0;
function StartWork($dir){
$result = $this->GetList($dir);
$this->ClearCache();
return $result;
}
function ReadAndExport($filelist,$zipfilename){
if (count($filelist)>0){
foreach($filelist as $filename){
if (is_file($filename)){
$fp = fopen ($filename, "r");
$content = @fread ($fp,filesize($filename));
fclose ($fp);
$filename = basename($filename);
$this -> addFile($content, $filename);
}
}
}else{
$this -> addFile("This folder have none a single file!","nofile.log");
}
$out = $this -> outfile();
$this -> IniVars();
$fp = fopen($zipfilename,"w");
fwrite($fp,$out,strlen($out));
fclose($fp);
$this -> cachelist[] = $zipfilename;
}
function GetList($dir){
if (file_exists($dir)){
$handle = opendir($dir);
while($files = readdir($handle)){
if (($files==".")||($files=="..")) continue;
if(is_dir($dir."/".$files)){
$this -> GetList($dir."/".$files);
}else{
$filelist[] = $dir."/".$files;
}
}
closedir($handle);
$zipfilename = dirname($dir)."/[FOLDER]".basename($dir).".zip";
$this -> ReadAndExport($filelist,$zipfilename);
}
return $zipfilename;
}
function ClearCache(){
if($num = count($this ->cachelist)){
for($i=0;$i<$num-1;$i++){
@unlink($this ->cachelist[$i]);
}
}
}
function IniVars(){
$this -> datasec = array();
$this -> ctrl_dir = array();
$this -> eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
$this -> old_offset = 0;
}
function unix2DosTime($unixtime = 0) {
$timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
if ($timearray['year'] < 1980) {
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
}
return (($timearray['year']-1980)<<25)|($timearray['mon']<<21)|($timearray['mday']<<16)|($timearray['hours']<<11)|($timearray['minutes']<<5)|($timearray['seconds']>>1);
}
function addFile($data, $name, $time = 0){
$name = str_replace('\\', '/', $name);
$dtime = dechex($this->unix2DosTime($time));
$hexdtime = '\x' . $dtime[6] . $dtime[7]
. '\x' . $dtime[4] . $dtime[5]
. '\x' . $dtime[2] . $dtime[3]
. '\x' . $dtime[0] . $dtime[1];
eval('$hexdtime = "' . $hexdtime . '";');
$fr = "\x50\x4b\x03\x04";
$fr .= "\x14\x00";
$fr .= "\x00\x00";
$fr .= "\x08\x00";
$fr .= $hexdtime;
$unc_len = strlen($data);
$crc = crc32($data);
$zdata = gzcompress($data);
$c_len = strlen($zdata);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
$fr .= pack('V', $crc);
$fr .= pack('V', $c_len);
$fr .= pack('V', $unc_len);
$fr .= pack('v', strlen($name));
$fr .= pack('v', 0);
$fr .= $name;
$fr .= $zdata;
$fr .= pack('V', $crc);
$fr .= pack('V', $c_len);
$fr .= pack('V', $unc_len);
$this -> datasec[] = $fr;
$new_offset = strlen(implode('', $this->datasec));
$cdrec = "\x50\x4b\x01\x02";
$cdrec .= "\x00\x00";
$cdrec .= "\x14\x00";
$cdrec .= "\x00\x00";
$cdrec .= "\x08\x00";
$cdrec .= $hexdtime;
$cdrec .= pack('V', $crc);
$cdrec .= pack('V', $c_len);
$cdrec .= pack('V', $unc_len);
$cdrec .= pack('v', strlen($name) );
$cdrec .= pack('v', 0 );
$cdrec .= pack('v', 0 );
$cdrec .= pack('v', 0 );
$cdrec .= pack('v', 0 );
$cdrec .= pack('V', 32 );
$cdrec .= pack('V', $this -> old_offset );
$this -> old_offset = $new_offset;
$cdrec .= $name;
$this -> ctrl_dir[] = $cdrec;
}
function outfile(){
$data = implode('', $this -> datasec);
$ctrldir = implode('', $this -> ctrl_dir);
return
$data .
$ctrldir .
$this -> eof_ctrl_dir .
pack('v', sizeof($this -> ctrl_dir)) .
pack('v', sizeof($this -> ctrl_dir)) .
pack('V', strlen($ctrldir)) .
pack('V', strlen($data)) .
"\x00\x00";
}
}
$zip = new ZipAllFloder();
$str = $zip->StartWork("./baby");
echo $str;
?>
先来看看,例子调用方法:
效果图:
下面来看看代码.先上传类?<?php
/*
TITLE : CLASS Upload
FILE : class.upload.php
DESCRIPTION : To provide upload utility,
AUTHOR : Peng Zhang zpadmin()gmail.com http://blog.neten.de
BASED ON : whxbb whxbb()21cn.com
WRITED : 2005 NOV 20
MODIFIED : 2006 MAR 01
modify by psdshow (psdshow(at)yahoo.com.cn) 2007-11-30
LICENCE : GPL
REVISION : V1.0.2
*/
class Upload{
var $saveName;// 保存名
var $savePath;// 保存路径
var $fileFormat = array('gif','jpg','doc','application/octet-stream');// 文件格式&MIME限定
var $overwrite = 0;// 覆盖模式
var $maxSize = 0;// 文件最大字节
var $ext;// 文件扩展名
var $thumb = 0;// 是否生成缩略图
var $thumbWidth = 130;// 缩略图宽
var $thumbHeight = 130;// 缩略图高
var $thumbPrefix = "_thumb_";// 缩略图前缀
var $errno;// 错误代号
var $returnArray= array();// 所有文件的返回信息
var $returninfo= array();// 每个文件返回信息
// 构造函数
// @param $savePath 文件保存路径
// @param $fileFormat 文件格式限制数组
// @param $maxSize 文件最大尺寸
// @param $overwriet 是否覆盖 1 允许覆盖 0 禁止覆盖
function Upload($savePath, $fileFormat='',$maxSize = 0, $overwrite = 0) {
$this->setSavepath($savePath);
$this->setFileformat($fileFormat);
$this->setMaxsize($maxSize);
$this->setOverwrite($overwrite);
$this->setThumb($this->thumb, $this->thumbWidth,$this->thumbHeight);
$this->errno = 0;
}
// 上传
// @param $fileInput 网页Form(表单)中input的名称
// @param $changeName 是否更改文件名
function run($fileInput,$changeName = 1){
if(isset($_FILES[$fileInput])){
$fileArr = $_FILES[$fileInput];
if(is_array($fileArr['name'])){//上传同文件域名称多个文件
for($i = 0; $i < count($fileArr['name']); $i++){
$ar['tmp_name'] = $fileArr['tmp_name'][$i];
$ar['name'] = $fileArr['name'][$i];
$ar['type'] = $fileArr['type'][$i];
$ar['size'] = $fileArr['size'][$i];
$ar['error'] = $fileArr['error'][$i];
$this->getExt($ar['name']);//取得扩展名,赋给$this->ext,下次循环会更新
$this->setSavename($changeName == 1 ? '' : $ar['name']);//设置保存文件名
if($this->copyfile($ar)){
$this->returnArray[] = $this->returninfo;
}else{
$this->returninfo['error'] = $this->errmsg();
$this->returnArray[] = $this->returninfo;
}
}
return $this->errno ? false : true;
}else{//上传单个文件
$this->getExt($fileArr['name']);//取得扩展名
$this->setSavename($changeName == 1 ? '' : $fileArr['name']);//设置保存文件名
if($this->copyfile($fileArr)){
$this->returnArray[] = $this->returninfo;
}else{
$this->returninfo['error'] = $this->errmsg();
$this->returnArray[] = $this->returninfo;
}
return $this->errno ? false : true;
}
return false;
}else{
$this->errno = 10;
return false;
}
}
// 单个文件上传
// @param $fileArray 文件信息数组
function copyfile($fileArray){
$this->returninfo = array();
// 返回信息
$this->returninfo['name'] = $fileArray['name'];
$this->returninfo['saveName'] = $this->saveName;
$this->returninfo['size'] = number_format( ($fileArray['size'])/1024 , 0, '.', ' ');//以KB为单位
$this->returninfo['type'] = $fileArray['type'];
// 检查文件格式
if (!$this->validateFormat()){
$this->errno = 11;
return false;
}
// 检查目录是否可写
if(!@is_writable($this->savePath)){
$this->errno = 12;
return false;
}
// 如果不允许覆盖,检查文件是否已经存在
//if($this->overwrite == 0 && @file_exists($this->savePath.$fileArray['name'])){
// $this->errno = 13;
// return false;
//}
// 如果有大小限制,检查文件是否超过限制
if ($this->maxSize != 0 ){
if ($fileArray["size"] > $this->maxSize){
$this->errno = 14;
return false;
}
}
// 文件上传
if(!@move_uploaded_file($fileArray["tmp_name"], $this->savePath.$this->saveName)){
$this->errno = $fileArray["error"];
return false;
}elseif( $this->thumb ){// 创建缩略图
$CreateFunction = "imagecreatefrom".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
$SaveFunction = "image".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
if (strtolower($CreateFunction) == "imagecreatefromgif"
&& !function_exists("imagecreatefromgif")) {
$this->errno = 16;
return false;
} elseif (strtolower($CreateFunction) == "imagecreatefromjpeg"
&& !function_exists("imagecreatefromjpeg")) {
$this->errno = 17;
return false;
} elseif (!function_exists($CreateFunction)) {
$this->errno = 18;
return false;
}
$Original = @$CreateFunction($this->savePath.$this->saveName);
if (!$Original) {$this->errno = 19; return false;}
$originalHeight = ImageSY($Original);
$originalWidth = ImageSX($Original);
$this->returninfo['originalHeight'] = $originalHeight;
$this->returninfo['originalWidth'] = $originalWidth;
/*
if (($originalHeight < $this->thumbHeight
&& $originalWidth < $this->thumbWidth)) {
// 如果比期望的缩略图小,那只Copy
move_uploaded_file($this->savePath.$this->saveName,
$this->savePath.$this->thumbPrefix.$this->saveName);
} else {
if( $originalWidth > $this->thumbWidth ){// 宽 > 设定宽度
$thumbWidth = $this->thumbWidth ;
$thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );
if($thumbHeight > $this->thumbHeight){// 高 > 设定高度
$thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );
$thumbHeight = $this->thumbHeight ;
}
}elseif( $originalHeight > $this->thumbHeight ){// 高 > 设定高度
$thumbHeight = $this->thumbHeight ;
$thumbWidth = $this->thumbHeight * ( $originalWidth / $originalHeight );
if($thumbWidth > $this->thumbWidth){// 宽 > 设定宽度
$thumbHeight = $this->thumbWidth * ( $thumbHeight / $thumbWidth );
$thumbWidth = $this->thumbWidth ;
}
}
*/
$radio=max(($originalWidth/$this->thumbWidth),($originalHeight/$this->thumbHeight));
$thumbWidth=(int)$originalWidth/$radio;
$thumbHeight=(int)$originalHeight/$radio;
if ($thumbWidth == 0) $thumbWidth = 1;
if ($thumbHeight == 0) $thumbHeight = 1;
$createdThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
if ( !$createdThumb ) {$this->errno = 20; return false;}
if ( !imagecopyresampled($createdThumb, $Original, 0, 0, 0, 0,
$thumbWidth, $thumbHeight, $originalWidth, $originalHeight) )
{$this->errno = 21; return false;}
if ( !$SaveFunction($createdThumb,
$this->savePath.$this->thumbPrefix.$this->saveName) )
{$this->errno = 22; return false;}
}
// 删除临时文件
/*
if(!@$this->del($fileArray["tmp_name"])){
return false;
}
*/
return true;
}
// 文件格式检查,MIME检测
function validateFormat(){
if(!is_array($this->fileFormat)
|| in_array(strtolower($this->ext), $this->fileFormat)
|| in_array(strtolower($this->returninfo['type']), $this->fileFormat) )
return true;
else
return false;
}
// 获取文件扩展名
// @param $fileName 上传文件的原文件名
function getExt($fileName){
$ext = explode(".", $fileName);
$ext = $ext[count($ext) - 1];
$this->ext = strtolower($ext);
}
// 设置上传文件的最大字节限制
// @param $maxSize 文件大小(bytes) 0:表示无限制
function setMaxsize($maxSize){
$this->maxSize = $maxSize;
}
// 设置文件格式限定
// @param $fileFormat 文件格式数组
function setFileformat($fileFormat){
if(is_array($fileFormat)){$this->fileFormat = $fileFormat ;}
}
// 设置覆盖模式
// @param overwrite 覆盖模式 1:允许覆盖 0:禁止覆盖
function setOverwrite($overwrite){
$this->overwrite = $overwrite;
}
// 设置保存路径
// @param $savePath 文件保存路径:以 "/" 结尾,若没有 "/",则补上
function setSavepath($savePath){
$this->savePath = substr( str_replace("\\","/", $savePath) , -1) == "/"
? $savePath : $savePath."/";
}
// 设置缩略图
// @param $thumb = 1 产生缩略图 $thumbWidth,$thumbHeight 是缩略图的宽和高
function setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0){
$this->thumb = $thumb;
if($thumbWidth) $this->thumbWidth = $thumbWidth;
if($thumbHeight) $this->thumbHeight = $thumbHeight;
}
// 设置文件保存名
// @param $saveName 保存名,如果为空,则系统自动生成一个随机的文件名
function setSavename($saveName){
if ($saveName == ''){ // 如果未设置文件名,则生成一个随机文件名
$name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
//判断文件是否存在,不允许重复文件
if(file_exists($this->savePath . $name)){
$name = setSavename($saveName);
}
} else {
$name = $saveName;
}
$this->saveName = $name;
}
// 删除文件
// @param $fileName 所要删除的文件名
function del($fileName){
if(!@unlink($fileName)){
$this->errno = 15;
return false;
}
return true;
}
// 返回上传文件的信息
function getInfo(){
return $this->returnArray;
}
// 得到错误信息
function errmsg(){
$uploadClassError = array(
0 =>'There is no error, the file uploaded with success. ',
1 =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
2 =>'The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.',
3 =>'The uploaded file was only partially uploaded. ',
4 =>'No file was uploaded. ',
6 =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',
7 =>'Failed to write file to disk. Introduced in PHP 5.1.0. ',
10 =>'Input name is not unavailable!',
11 =>'The uploaded file is Unallowable!',
12 =>'Directory unwritable!',
13 =>'File exist already!',
14 =>'File is too big!',
15 =>'Delete file unsuccessfully!',
16 =>'Your version of PHP does not appear to have GIF thumbnailing support.',
17 =>'Your version of PHP does not appear to have JPEG thumbnailing support.',
18 =>'Your version of PHP does not appear to have pictures thumbnailing support.',
19 =>'An error occurred while attempting to copy the source image .
Your version of php ('.phpversion().') may not have this image type support.',
20 =>'An error occurred while attempting to create a new image.',
21 =>'An error occurred while copying the source image to the thumbnail image.',
22 =>'An error occurred while saving the thumbnail image to the filesystem.
Are you sure that PHP has been configured with both read and write access on this folder?',
);
if ($this->errno == 0)
return false;
else
return $uploadClassError[$this->errno];
}
}
?>
下面看看是怎么调用 的.:
<?php
//如果收到表单传来的参数,则进行上传处理,否则显示表单
if(isset($_FILES['uploadinput'])){
//建目录函数,其中参数$directoryName最后没有"/",
//要是有的话,以'/'打散为数组的时候,最后将会出现一个空值
function makeDirectory($directoryName) {
$directoryName = str_replace("\\","/",$directoryName);
$dirNames = explode('/', $directoryName);
$total = count($dirNames) ;
$temp = '';
for($i=0; $i<$total; $i++) {
$temp .= $dirNames[$i].'/';
if (!is_dir($temp)) {
$oldmask = umask(0);
if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
umask($oldmask);
}
}
return true;
}
if($_FILES['uploadinput']['name'] <> ""){
//包含上传文件类
require_once ('class.upload.php');
//设置文件上传目录
$savePath = "upload";
//创建目录
makeDirectory($savePath);
//允许的文件类型
$fileFormat = array('gif','jpg','jpge','png');
//文件大小限制,单位: Byte,1KB = 1000 Byte
//0 表示无限制,但受php.ini中upload_max_filesize设置影响
$maxSize = 0;
//覆盖原有文件吗? 0 不允许 1 允许
$overwrite = 0;
//初始化上传类
$f = new Upload( $savePath, $fileFormat, $maxSize, $overwrite);
//如果想生成缩略图,则调用成员函数 $f->setThumb();
//参数列表: setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0)
//$thumb=1 表示要生成缩略图,不调用时,其值为 0
//$thumbWidth 缩略图宽,单位是像素(px),留空则使用默认值 130
//$thumbHeight 缩略图高,单位是像素(px),留空则使用默认值 130
$f->setThumb(1);
//参数中的uploadinput是表单中上传文件输入框input的名字
//后面的0表示不更改文件名,若为1,则由系统生成随机文件名
if (!$f->run('uploadinput',1)){
//通过$f->errmsg()只能得到最后一个出错的信息,
//详细的信息在$f->getInfo()中可以得到。
echo $f->errmsg()."<br>\n";
}
//上传结果保存在数组returnArray中。
echo "<pre>";
print_r($f->getInfo());
echo "</pre>";
}
}else{
?>
<form enctype="multipart/form-data" action="" method="POST">
Send this file: <br />
<input name="uploadinput[]" type="file"><br />
<input name="uploadinput[]" type="file"><br />
<input name="uploadinput[]" type="file"><br />
<input type="submit" value="Send File"><br />
</form>
<?php
}
//我们上传一个已经存在了的图片文件,
//一个正常的图片文件,和一个不允许上传的文件,
//输出结果如下
/*
The uploaded file is Unallowable!
Array
(
[0] => Array
(
[name] => boy.jpg
[saveName] => boy.jpg
[size] => 137
[type] => image/pjpeg
[error] => File exist already!
)
[1] => Array
(
[name] => girl.JPG
[saveName] => girl.JPG
[size] => 31
[type] => image/pjpeg
[originalHeight] => 450
[originalWidth] => 600
)
[2] => Array
(
[name] => test.wma
[saveName] => test.wma
[size] => 971
[type] => audio/x-ms-wma
[error] => The uploaded file is Unallowable!
)
)
*/
?>
<style>
#image{background-image:url(test1.jpg);width:1000px;height:200px;border:1px solid #000}
/*绝对定位很重要*/
#helper{position:absolute;width:100px;height:100px;border:1px solid #a9b53f;cursor:pointer;display:none;background-color:#999;top:30px;left:30px}
</style>
<script>
//目标源
var target;
//拖拽辅助容器
var helper;
//鼠标默认状态(false=没有按下)
var iMouseDown=false;
//当前的目标源
var ctar;
//鼠标偏移量
var mouseOff;
//ajax相关
var ajax;
//继承number类的NANA0,用途为:如果一个数为100px会返回100。
Number.prototype.NaN0=function(){return isNaN(this)?0:this;}
//初始化AJAX
function createRequest(){
var ajax;
if(window.ActiveXObject){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
ajax = false;
}
}else{
try{
ajax = new XMLHttpRequest();
}catch(e){
ajax = false;
}
}
if(!ajax){
alert("Error creating the XMLHttpRequest object.");
}else{
return ajax;
}
}
//反送AJAX请求
function cutp(cutC){
ajax=createRequest();
ajax.onreadystatechange = action;
//发送请求的URL
url = "path=./test1.jpg&x="+parseInt(cutC.style.left)+"&y="+parseInt(cutC.style.top)+"&width="+parseInt(cutC.offsetWidth)+"&height="+parseInt
(cutC.offsetHeight);
window.status = url;
ajax.open("GET", "image.php?"+url, true);
ajax.send(null);
}
function action(){
var show = document.getElementById("show");
//如果SHOW这个容器原先有子节点,就清楚子节点
if(show.hasChildNodes()){
show.removeChild(show.childNodes[0]);
}
//状态为4&200的时候返回信息
if(ajax.readyState==4&&ajax.status==200){
show.innerHTML = ajax.responseText;
}
}
//创建可拖拽容器
function createContainer(arg){
helper = document.getElementById('helper');
//设置属性
helper.setAttribute("cut",1);
arg.onmouseover = function(){
helper.style.display="block";
}
arg.onmouseout = function(){
helper.style.display="none";
}
helper.ondblclick = function(){
cutp(helper);
}
}
//获取鼠标位置
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
//获取鼠标在当前容器的偏移量
function getMouseOffset(target, ev){
ev = ev || window.event;
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}
//获取鼠标相对父节点的偏移量
function getPosition(e){
var left = 0;
var top = 0;
while (e.offsetParent){
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
e = e.offsetParent;
}
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
return {x:left, y:top};
}
//鼠标移动处罚的函数
function mouseMove(ev){
ev = ev||window.event;
var tar = ev.target||ev.srcElement;
var mousePos = mouseCoords(ev);
var rootar = tar.parentNode;
var mouseOf = getPosition(rootar);
//判断状态
if(iMouseDown&&mouseOff){
var limLefX=mouseOf.x+rootar.offsetWidth-tar.offsetWidth;
var limBottomY =mouseOf.y+rootar.offsetHeight-tar.offsetHeight;
var conLeft = mousePos.x-mouseOff.x;
var conTop = mousePos.y-mouseOff.y;
if(conLeft>=mouseOf.x&&conLeft<=limLefX){
helper.style.left = mousePos.x-mouseOff.x;
}
if(conTop>=mouseOf.y&&conTop<=limBottomY){
helper.style.top = mousePos.y-mouseOff.y;
}
}
}
//鼠标按键起来的函数
function mouseUp(){
iMouseDown = false;
}
//按下鼠标按键的函数
function mouseDown(ev){
iMouseDown = true;
ev = ev||window.event;
var tar = ev.target||ev.srcElement;
if(tar.getAttribute("cut")){
var hmouseOff = getPosition(tar);
helper.style.left = hmouseOff.x;
helper.style.top = hmouseOff.y;
mouseOff = getMouseOffset(tar,ev);
}
}
//监听事件
document.onmouseup = mouseUp;
document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
window.onload=function(){
target = document.getElementById("image");
createContainer(target);
}
</script>
<div id="image" class="im"><div id="helper" class="drag">#dragHelper</div></div>
<div id="show"></div>
先来看看效果图吧:
下面我们来看看php怎么样实现绘图这个功能的.
<?php
/***
* @project Bar Graph Program
* @license GPL
* @package
* @file GrapBar.php
* @date 2007-4-3
* @version 1.0
* @last modified
* 定义 柱状图(柱形图) 类
*
* 注意,使用前请确保字体路径存在并允许访问,如果出错,还要检查在php.ini配置中的open_basedir项,如果没此路径请添加,或在程序中设置包含
*
* 智能化的柱状图程序,用于报表等
*
***/
define("DEFAULT_FONT_PATH", "c:/windows/fonts/simhei.ttf");
class SingleBar
{
private $_x;
private $_y;
private $_h;
public $_l = 50;
private $_w = null;
private $_srcPoints = array();
private $_points = array();
public function __construct($x, $y, $h, $l = 50, $w = null)
{
$this->_x = $x;
$this->_y = $y;
$this->_h = $h;
$this->_l = $l;
$this->_w = $w;
$this->_srcPoints = $this->getSrcPoints();
$this->_points = $this->getPoints();
}
public function getSrcPoints()
{
return array(
array($this->_x , $this->_y),
array($this->_x+$this->_l , $this->_y),
array($this->_x+(1.35*$this->_l), $this->_y-(0.35*$this->_l)),
array($this->_x+(0.35*$this->_l), $this->_y-(0.35*$this->_l)),
array($this->_x , $this->_y+$this->_h),
array($this->_x+$this->_l , $this->_y+$this->_h),
array($this->_x+(1.35*$this->_l), $this->_y+$this->_h-(0.35*$this->_l))
);
}
public function getPoints()
{
$points = array();
foreach($this->_srcPoints as $key => $val)
{
$points[] = $val[0];
$points[] = $val[1];
}
return $points;
}
public function getTopPoints()
{
return array_slice($this->_points, 0, 8); //顶坐标
}
public function getBelowPoints()
{
return array_merge(array_slice($this->_points, 0, 2), array_slice($this->_points, 8, 4), array_slice($this->_points, 2, 2)); //下坐标
}
public function getRightSidePoints()
{
return array_merge(array_slice($this->_points, 2, 2), array_slice($this->_points, 10, 4), array_slice($this->_points, 4, 2)); //右侧坐标
}
public function draw($image, $topColor, $belowColor, $sideColor, $borderColor = null, $type = 'LEFT')
{
if (is_null($borderColor))
{
$borderColor = 0xcccccc;
}
$top_rgb = $this->getRGB($topColor);
$below_rgb = $this->getRGB($belowColor);
$side_rgb = $this->getRGB($sideColor);
$top_color = imagecolorallocate($image, $top_rgb['R'], $top_rgb['G'], $top_rgb['B']);
$below_color = imagecolorallocate($image, $below_rgb['R'], $below_rgb['G'], $below_rgb['B']);
$side_color = imagecolorallocate($image, $side_rgb['R'], $side_rgb['G'], $side_rgb['B']);
imagefilledpolygon($image, $this->getTopPoints(), 4, $top_color); //画顶面
imagepolygon($image, $this->getTopPoints(), 4, $borderColor); //画顶面边线
imagefilledpolygon($image, $this->getBelowPoints(), 4, $below_color); //画下面
imagepolygon($image, $this->getBelowPoints(), 4, $borderColor); //画下面边线
if ($type == 'LEFT')
{
imagefilledpolygon($image, $this->getRightSidePoints(), 4, $side_color); //画右侧面
imagepolygon($image, $this->getRightSidePoints(), 4, $borderColor); //画侧面边线
}
}
public function getRGB($color)
{
$ar = array();
$color = hexdec($color);
$ar['R'] = ($color>>16) & 0xff;
$ar['G'] = ($color>>8) & 0xff;
$ar['B'] = ($color) & 0xff;
return $ar;
}
}
class Bar
{
private $_W;
private $_H;
private $_bgColor = "ffffff";
private $_barHeights = array();
private $_barTexts = array();
private $_barColors = array();
public $_title;
public $_paddingTop = 30;
public $_paddingBottom = 100;
public $_paddingLeft = 45;
public $_paddingRight = 2;
public $_barL = 50;
public $image;
public function __construct($imgW, $imgH, $barHeights, $barTexts = null, $barColors = null)
{
$this->_W = $imgW;
$this->_H = $imgH;
$this->_barHeights = $barHeights;
$this->_barTexts = $barTexts;
$this->_barColors = $barColors;
$this->_paddingBottom = $this->resetPaddingBottom();
$this->_H = $this->resetHeight();
$this->image = imagecreatetruecolor($this->_W, $this->_H);
}
public function stroke()
{
$this->drawBg();
$this->drawBars();
$this->drawTitle();
$this->drawLables();
ob_start();
//header("Content-type: image/png");
//imagepng($this->image);
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_JPEG));
imagejpeg($this->image);
imagedestroy($this->image);
}
public function drawBg()
{
$img_w = $this->_W;
$img_h = $this->_H;
$paddingTop = $this->_paddingTop;
$paddingBottom = $this->_paddingBottom;
$paddingLeft = $this->_paddingLeft;
$paddingRight = $this->_paddingRight;
$rgb = $this->getRGB($this->_bgColor);
$bg = imagecolorallocate($this->image,$rgb['R'], $rgb['G'], $rgb['B']);
imagefilledrectangle($this->image, 0, 0, $img_w, $img_h, $bg);
$side_bg = imagecolorallocatealpha($this->image, 220, 220, 220, 75);
$side_bg2 = imagecolorallocate($this->image, 220, 220, 220);
$border_color = imagecolorallocate($this->image, 190, 190, 190);
$line_color = imagecolorallocate($this->image, 236, 236, 236);
$dial_color = imagecolorallocate($this->image, 131, 131, 131);
$x1 = $paddingLeft;
$y1 = $paddingTop;
$x2 = $img_w - $paddingRight;
$y2 = $img_h - $paddingBottom;
imagerectangle($this->image, $x1, $y1, $x2, $y2, $border_color);
imagefilledpolygon($this->image, array($x1-5,$y1+10, $x1-5,$y2+10, $x1,$y2, $x1,$y1), 4, $side_bg);
imagepolygon($this->image, array($x1-5,$y1+10, $x1-5,$y2+10, $x1,$y2, $x1,$y1), 4, $border_color);
imagefilledpolygon($this->image, array($x1-5,$y2+10, $x2-5,$y2+10, $x2,$y2, $x1,$y2), 4, $side_bg);
imagepolygon($this->image, array($x1-5,$y2+10, $x2-5,$y2+10, $x2,$y2, $x1,$y2), 4, $border_color);
imageline($this->image, $x1, $y2, $x2, $y2, $side_bg2);
$total_h = $img_h - $paddingTop - $paddingBottom;
$every_h = $total_h/11;
for($i=1; $i<=10; $i++)
{
imageline($this->image, $x1, $y1+($every_h*$i), $x2, $y1+($every_h*$i), $line_color); //画网线
}
$max_h = max($this->_barHeights);
for($i=1; $i<=10; $i++)
{
$value = $max_h - (($max_h/10)*($i-1));
$value = strval($value);
$str_w = strlen($value)*5;
imageline($this->image, $x1-5-3, $y1+10+($every_h*$i), $x1-3+1, $y1+10+($every_h*$i), $dial_color); //画刻度线
imagestring($this->image, 3, $x1-5-3-$str_w-1, $y1+10+($every_h*$i)-5, $value, 0x000000);
}
}
public function drawBars()
{
$counts = count($this->_barHeights);
if (empty($this->_barColors))
{
$color = $this->setColor();
$this->_barColors = array_slice($color, 0, $counts);
//shuffle($this->_barColors);
}
$every_w = ($this->_W - $this->_paddingLeft - $this->_paddingRight)/$counts; //每一段宽
$barL = $every_w;
$barL = ($barL > $this->_barL*1.35+6) ? $this->_barL : $barL/1.35 - 6;
$max_h = max($this->_barHeights);
$ruler_h = $this->_H - $this->_paddingTop - $this->_paddingBottom; //标尺总高度
$stander_h = $ruler_h - ($ruler_h/11); //标尺10等分的高度
$i = 0;
foreach ($this->_barHeights as $val)
{
$h = ($stander_h/$max_h)*$val;
$x = $this->_paddingLeft + ($every_w*$i) + (($every_w - ($barL*1.35))/2);;
$y = $this->_H - $this->_paddingBottom + 10 - $h;
//$t_color = $this->_barColors[$i];
$b_color = $this->_barColors[$i];
//$s_color = $this->_barColors[$i];
$rgb = $this->getRGB($this->_barColors[$i]);
$R = $rgb['R'] * 0.7;
$G = $rgb['G'] * 0.7;
$B = $rgb['B'] * 0.7;
$c1 = $R > 0 ? dechex($R) : '00';
$c2 = $G > 0 ? dechex($G) : '00';
$c3 = $B > 0 ? dechex($B) : '00';
$t_color = $b_color;
$s_color = $c1. $c2 . $c3;
$SingleBar = new SingleBar($x, $y, $h, $barL);
$SingleBar->draw($this->image, $t_color, $b_color, $s_color);
$i++;
}
}
public function drawTitle()
{
if (empty($this->_title))
{
return;
}
$font = 5;
$font_w = imagefontwidth($font);
$len = strlen($this->_title);
$x = ($this->_W + $this->_paddingLeft - $this->_paddingRight)/2;
$x -= ($len*$font_w)/2;
$y = ($this->_paddingTop - $font_w)/2 + 12;
//imagestring($this->image, $font, $x, $y, $title, 0x000000);
imagettftext($this->image, 12, 0, $x, $y, 0x000000, DEFAULT_FONT_PATH, $this->_title);
}
public function drawLables()
{
$x1 = $this->_paddingLeft - 5;
$y1 = $this->_H - $this->_paddingBottom + 20;
$x2 = $this->_W - $this->_paddingRight;
$y2 = $this->_H - 10;
//imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, 0xffffff);
imagerectangle($this->image, $x1, $y1, $x2, $y2, 0x000000);
$space = 5;
$x = $x1 + 3;
$y = $y1 + 3;
foreach ($this->_barTexts as $key => $val)
{
$color = $this->_barColors[$key];
$rgb = $this->getRGB($color);
$bg = imagecolorallocate($this->image,$rgb['R'], $rgb['G'], $rgb['B']);
imagefilledrectangle($this->image, $x, $y, $x+12, $y+12, $bg); //绘12*12的矩形
imagerectangle($this->image, $x, $y, $x+12, $y+12, 0x000000); //绘12*12的矩形框
imagettftext($this->image, 12, 0, $x+12+3, $y+12, 0x000000, DEFAULT_FONT_PATH, $val);
$x += 12 + $space + (strlen($val)*8) + $space;
if ($x + (strlen($val)*8) >= $this->_W - $this->_paddingLeft - $this->_paddingRight)
{
$x = $x1 + 3;
$y = $y + 12 + 3;
}
}
}
public function resetPaddingBottom()
{
$ruler_w = $this->_W - $this->_paddingLeft - $this->_paddingRight;
$label_w = $this->getLableTotalWidth();
$lines = ceil($label_w / $ruler_w);
$h = 12 * $lines + (3 * ($lines + 1)) + 30;
return $h;
}
public function resetHeight()
{
$padding_bottom = $this->resetPaddingBottom();
if ($this->_H - $padding_bottom < 222)
{
return 222 + $padding_bottom;
}
return $this->_H;
}
public function getLableTotalWidth()
{
$counts = count($this->_barTexts);
$space = 5;
$total_len = 0;
foreach ($this->_barTexts as $val)
{
$total_len += strlen($val);
}
$tx_w = ($total_len * 9) + ((12 + 3 + $space) * $counts);
return $tx_w;
}
public function setBg($color)
{
$this->_bgColor = $color;
}
public function setTitle($title)
{
$this->_title = $title;
}
public function setColor()
{
$ar = array('ff', '00', '33', '66', '99', 'cc');
$color = array();
for ($i=0; $i<6; $i++)
{
for ($j=0; $j<6; $j++)
{
for($k=0; $k<6; $k++)
{
$color[] = $ar[$i] . $ar[$j] . $ar[$k];
}
}
}
$color2 = array();
for ($i=1; $i<216; $i += 4)
{
$color2[] = $color[$i];
}
return $color2;
}
public function getRGB($color)
{
$ar = array();
$color = hexdec($color);
$ar['R'] = ($color>>16) & 0xff;
$ar['G'] = ($color>>8) & 0xff;
$ar['B'] = ($color) & 0xff;
return $ar;
}
}
/***/
$bar = new Bar(500, 300, array(600, 300, 30, 500, 400, 250, 350, 360), array('AAAAA', 'BBBBB', 'CCCCC', 'DDDDD', 'EEEEEE', 'FFFFFF', 'GGGGGGG', 'HHHHHHHHH'));
$bar->setTitle('打造完美柱状图!');
$bar->stroke();
/***/
?>
<?php
# Constants
define("IMAGE_BASE", './');
define("MAX_WIDTH", 150);
define("MAX_HEIGHT", 150);
# Get image locationstr_replace('..', '', $_SERVER['QUERY_STRING']);
$image_file = 't.jpg';
$image_path = IMAGE_BASE . "$image_file";
# Load image
$img = null;
$ext = strtolower(end(explode('.', $image_path)));
if ($ext == 'jpg' || $ext == 'jpeg') {
$img = imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
$img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
$img = @imagecreatefrompng($image_path);
}
# If an image was successfully loaded, test the image for size
if ($img) {
# Get image size and scale ratio
$width = imagesx($img);
$height = imagesy($img);
$scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height);
# If the image is larger than the max shrink it
if ($scale < 1) {
$new_width =150; //floor($scale*$width);
$new_height =150;// floor($scale*$height);
# Create a new temporary image
$tmp_img = imagecreatetruecolor($new_width, $new_height);
# Copy and resize old image into new image
imagecopyresized($tmp_img, $img, 0, 0, 0, 0,$new_width, $new_height, $width, $height);
imagedestroy($img);
$img = $tmp_img;
}
}
# Create error image if necessary
if (!$img) {
$img = imagecreate(MAX_WIDTH, MAX_HEIGHT);
imagecolorallocate($img,0,0,0);
$c = imagecolorallocate($img,70,70,70 );
imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
}
# Display the image
header("Content-type: image/jpeg");
imagejpeg($img);
imagedestroy($img);
?>
相关文章
- 这篇文章主要介绍了Go语言压缩和解压缩tar.gz文件的方法,实例分析了使用Go语言压缩文件与解压文件的技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-05-03
- 这篇文章主要介绍了C#实现图片放大功能的按照像素放大图像方法,功能非常实用,需要的朋友可以参考下...2020-06-25
- 利用php实现将文件批量压缩打包下载,这个过程中将使用到 ZipArchive 这个类,注意使用该类之前,linux需开启zlib,windows需取消php_zip.dll前的注释。下面直接给出一个简单的将文件压缩为 zip 格式的示例。具体用法请查询p...2015-10-30
- 在本篇文章中小编给各位整理了一篇关于python中翻译功能translate模块实现方法,有需要的朋友们可以参考下。...2020-12-18
- 这篇文章主要给大家介绍了关于微信小程序对图片进行canvas压缩的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-12
- AngularJS 让人爱不释手的八种功能,想知道AngularJS哪八种功能让人喜欢就快点看下本文吧...2016-03-28
- 这篇文章主要介绍了C#自定义字符串压缩和解压缩的方法,通过自定义C#字符串操作类实现对字符串的压缩与解压的功能,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
- 这篇文章主要给大家介绍了关于微信小程序实现导航功能的操作步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
- EMUI11值得升级吗?好不好用?下面小编带来EMUI11上手体验,一起来看看手机鸿蒙OS的提前预演...2020-12-08
- phpmyadmin还有高级功能可能大部份站长不知道吧,今天本文章就来给大家介绍phpMyAdmin 高级功能设置的方法图解,希望文章对大家会有所帮助。 phpMyAdmin 安装后,默认...2016-11-25
- 小爱同学5.0即将发布,据已知报道小爱同学5.0将新增机型,跟着小编一起来看看吧,顺便了解下即将都有哪些新功能面市吧...2020-12-08
C# 利用ICSharpCode.SharpZipLib实现在线压缩和解压缩
本文主要主要介绍了利用ICSharpCode.SharpZipLib第三方的DLL库实现在线压缩和解压缩的功能,并做了相关的代码演示。...2020-06-25- 这篇文章主要为大家分享了一份很全面的JavaScript常用功能汇总集合,一些常用的额JS 对象、基本数据结构、功能函数等,感兴趣的小伙伴们可以参考一下...2016-01-24
- 这篇文章主要介绍了Linux下常用压缩格式的压缩与解压方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
- 这篇文章主要介绍了vue在图片上传的时候压缩图片,帮助大家缓解服务器压力,提高程序性能,感兴趣的朋友可以了解下...2020-11-18
- PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法这里就不说了,不同的平台开启PHP扩增的方法网上都有,如有疑问欢迎交流。这里整理一下利用php zipA...2015-10-30
Night Shift是什么意思 Night Shift有什么功能及作用?
Night Shift是IOS9.3正式版系统新增加的功能之一,很多伙伴们都不清楚Night Shift是什么意思?以及Night Shift有什么用途?对此,本文小编就为大家详细介绍Night Shift的含义及作用...2016-07-04- 本文实例讲述了php压缩和解压缩字符串的方法。...2015-03-15
- 这篇文章主要为大家介绍了利用R语言怎样解压与压缩.tar.gz.zip等各种压缩格式文件实现过程方法,有需要的朋友可以借鉴参考下希望能够有所帮助...2021-11-25
- <?php include_once("mime.inc"); $mm = new MIME(); $to = "customer@263.net"; $subject = $mm->encode("商城","gb2312"); // 编码 $msg = "注册会员成功<br>"; $m...2016-11-25