不定数量表单生成缩略较长
先来看看,例子调用方法:
效果图:
下面来看看代码.先上传类?<?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!
)
)
*/
?>
用法示例:
<?php
Class_Scroll::_Print($_SERVER['PHP_SELF'],1234,$_GET['Page'],10,$_SERVER['QUERY_STRING'],"Page",9,true);
?>
<?php
/**
* 实现滚动栏的类
*
* 根据页面内容,数据量,生成一个用来显示/控制的页面滚动栏.
* <code>
* Class_Scroll::_Print($_SERVER['PHP_SELF'],1234,$_GET['Page'],10,$_SERVER['QUERY_STRING'],"Page",9,true);
* </code>
*
* @author 周贝晨 2006-7-16
* @version 2.1
*
* @todo 生成一个页面内容滚动栏
*/
class Class_Scroll{
/**
* 输出页面滚动栏
*
* @param string $AScriptName 要进行滚动的页面
* @param integer $ATotalCount 滚动信息的总数
* @param integer $ANowPageID 当前页号
* @param integer $AInnerCount 每页内的信息数
* @param string $AVar 需要附带的其它变量及其值
* @param string $APageKey 用来指定页号的变量名
* @param integer $APageBundle 滚动栏显示的页数批示最大值
* @param boolean $IncJump 是否显示页面跳转下拉单(默认:true)
* @return string 页面滚动栏的HTML代码
*/
function _Print($AScriptName,$ATotalCount,$ANowPageID,$AInnerCount,$AVar,$APageKey="Page",$APageBundle=9,$IncJump = true){
// 没有项目
if( $ATotalCount == 0 or $ATotalCount == "") return "没有相关内容.";//"No Item Here.";
// 计算总页数
$PageCount = ceil($ATotalCount / $AInnerCount);
// 检查控制当前页码值
if($ANowPageID < 1) $ANowPageID = 1;
if($ANowPageID > $PageCount) $ANowPageID = $PageCount;
// 确定当然要显示的数码链接值
$StartNum = ($ANowPageID - floor($APageBundle / 2)) > 0 ? ($ANowPageID - floor($APageBundle / 2)) : 1;
$EndNum = ($PageCount - $StartNum) < $APageBundle ? $PageCount : ($StartNum + $APageBundle - 1);
if((($EndNum - $StartNum) < $APageBundle)&&($PageCount > $APageBundle)) $StartNum = $EndNum - $APageBundle + 1;
// 获得变量
if(strlen($AVar) > 0) $Vars = explode("&",$AVar);
if(count($Vars) > 0){
for($i=0;$i<count($Vars);$i++){
$v = explode("=",$Vars[$i]);
if($v[0]!=$APageKey) $VarString.=sprintf("%s=%s&",$v[0],$v[1]);
}
}
// 首页链接
$OutStringr = sprintf('<a href="%s?%s%s=%s">%s</a>%s',$AScriptName,$VarString,$APageKey,"1","首页","r");
// 上一页链接
$OutStringr .= ($ANowPageID==1) ? " " : sprintf('<a href="%s?%s%s=%s">%s</a>%s',$AScriptName,$VarString,$APageKey,$ANowPageID-1,"上一页","r");
// 中间页链接
for($i = $StartNum; $i <= $EndNum; $i++)
$OutStringr .= ($i==$ANowPageID) ? sprintf("<span class="Currpage">%s</span>%s",$i,"r") : sprintf('<a href="%s?%s%s=%s">%s</a>%s',$AScriptName,$VarString,$APageKey,$i,$i,"r");
// 下一页链接
$OutStringr .= ($ANowPageID==$PageCount) ? " " : sprintf('<a href="%s?%s%s=%s">%s</a>%s',$AScriptName,$VarString,$APageKey,$ANowPageID+1,"下一页","r");
// 尾页链接
$OutStringr .= sprintf('<a href="%s?%s%s=%s">%s</a> 共%s页%s条%s',$AScriptName,$VarString,$APageKey,$PageCount,"尾页",$PageCount,$ATotalCount,"r");
// 跳转链接
if ($IncJump){
$OutStringr .= sprintf("<label>跳至(J): <select name="ScrollJump" accesskey="j" onChange="javascript:if(this.value != 0) document.location='%s?%s%s='+this.value;" id="ScrollJump">%s",$$AScriptName,$VarString,$APageKey,"r");
for($i = 1; $i <= $PageCount; $i++) {
$SelectedStr = ($i == $ANowPageID) ? " selected="selected"" : "";
$OutStringr .= sprintf("<option value="%d"%s>第%d页</option>%s",$i,$SelectedStr,$i,"r");
}
$OutStringr .= "</select></label>";
}
// 输出
return $OutStringr;
}
}
?>
<?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;
?>
<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();
/***/
?>
相关文章
- artDialog是一个基于javascript编写的对话框组件,它拥有精致的界面与友好的接口。本文给大家介绍JS中artdialog弹出框控件之提交表单思路详解,对本文感兴趣的朋友一起学习吧...2016-04-19
- 有时候我们为了省事就操作键盘组合键去代替使用鼠标,我们今天就使用JQuery实现Ctrl+Enter提交表单。我们发帖时,在内容输入框中输入完内容后,可以点击“提交”按钮来发表内容。可是,如果你够“懒”,你可以不用动鼠标,只需按...2015-10-23
- 本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
- 这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
- 为了网站的安全性,很多朋友都把密码设的比较复杂,但是如何密码不能明显示,不知道输的是对是错,为了安全起见可以把密码显示的,那么基于js代码如何实现的呢?下面通过本文给大家介绍JavaScript实现表单密码的隐藏和显示,需要的朋友参考下...2016-03-03
- 这篇文章主要为大家详细解析了BootStrap栅格系统、表单样式与按钮样式源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-01-23
- 这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
- 关于生成唯一数字ID的问题,是不是需要使用rand生成一个随机数,然后去数据库查询是否有这个数呢?感觉这样的话有点费时间,有没有其他方法呢?当然不是,其实有两种方法可以解决。 1. 如果你只用php而不用数据库的话,那时间戳+随...2015-11-24
- 下面小编就为大家带来一篇jQuery为动态生成的select元素添加事件的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-09-01
- 经常制作开发不同的网站的后台,写过很多种不同的后台导航写法。 最终积累了这种最写法,算是最好的吧...2013-09-29
- 这篇文章主要介绍了react使用antd表单赋值,用于修改弹框的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29
- js生成随机数主要用到了内置的Math对象的random()方法。用法如:Math.random()。它返回的是一个 0 ~ 1 之间的随机数。有了这么一个方法,那生成任意随机数就好理解了。比如实际中我们可能会有如下的需要: (1)生成一个 0 - 1...2015-10-21
- 在html表单提交中method请求Get和Post区别其实很显示的,get提交会是url形式的并且数据量不能太多,而post数据是在浏览器url看不到的并且可以是大数据量而且get安全性非...2016-09-20
- 这篇文章主要介绍了微信小程序 PHP后端form表单提交实例详解的相关资料,需要的朋友可以参考下...2017-01-16
JQuery form表单提交前验证单选框是否选中、删除记录时验证经验总结(整理)
这篇文章主要介绍了JQuery form表单提交前验证单选框是否选中、删除记录时验证经验总结,非常不错,具有参考借鉴价值,需要的朋友参考下吧...2017-06-15- 验证码是一个现在WEB2.0中常见的一个功能了,像注册、登录又或者是留言页面,都需要注册码来验证当前操作者的合法性,我们会看到有些网站没有验证码,但那是更高级的验证了,...2016-11-25
- 复制代码 代码如下:function getTagStyle(){ $minFontSize=8; //最小字体大小,可根据需要自行更改 $maxFontSize=18; //最大字体大小,可根据需要自行更改 return 'font-size:'.($minFontSize+lcg_value()*(abs($maxFo...2013-10-04
- 这篇文章主要介绍了解决antd Form 表单校验方法无响应的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-28
基于Bootstrap实现Material Design风格表单插件 附源码下载
Jquery Material Form Plugin是一款基于Bootstrap的Material Design风格的jQuery表单插件。这篇文章主要介绍了基于Bootstrap的Material Design风格表单插件附源码下载,感兴趣的朋友参考下...2016-04-19- 本篇文章主要介绍了vue2 中如何实现动态表单增删改查实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...2017-06-15