ajax图片上传剪切

 更新时间:2016年11月25日 16:29  点击:1798

允许用户以AJAX的方式上传图片
·允许用户选择图片的一定区域
·最后,提供一个裁减后图片的下载地址

我们将要用到三个文件

·index.php - 包含图片上传表单以及剪切界面
·upload.php - 提供上传功能
·crop.php - 提供剪切功能

从技术角度看,流程如下所示:

1.用户上传文件(index.php)
2.index.php将上传的图片POST到upload.php以处理上传图片程序,返回JSON数据包括图片名,长和宽。
3.根据JSON里的数据和innerHTML,我们将图片放在页面上
4.初始化javascript剪切工具
5.生成下载连接(crop.php)

让我们来看看index.php

index.php是我们的主要文件,用户通过他来上传和下载图片。

我们需要YUI提供的以下几个组件:
·yahoo-dom-event.js - 操作和解析DOM
·dragdrop - 基于图片剪切工具
·element - 基于图片剪切工具
·resize - 基于图片剪切工具
·connection - 为AJAX请求, 此例通过AJAX上传
·json - 解析JSON
·imagecropper - 我们最重要的工具

当然我们要用到 Yahoo combo handling并且加上上面提到的脚本和样式表:[code]<link rel="stylesheet" type="text/css"
href="http://yui.yahooapis.com/2.5.2/build/resize/assets/skins/sam/resize.css"
/>
<link rel="stylesheet" type="text/css"
href="http://yui.yahooapis.com/2.5.2/build/imagecropper/assets/skins/sam/imagecropper.css"
/>
<!-- js -->
<script type="text/javascript"
src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/dragdrop/dragdrop-min.js&2.5.2/build/element/element-beta-min.js&2.5.2/build/resize/resize-beta-min.js&2.5.2/build/imagecropper/imagecropper-beta-min.js&2.
5.2/build/connection/connection-min.js&2.5.2/build/json/json-min.js"></script>
[/code]然后用户一定会通过AJAX上传图片,所以我们在页面上加一个表单。[code]<form action="upload.php"
enctype="multipart/form-data" method="post" name="uploadForm"
id="uploadForm">
        Image :
<input type="file" name="uploadImage" id="uploadImage" />
<input type="button" id="uploadButton" value="Upload"/>
</form>
[/code]点击上传按钮来激活上传程序。[code]// add listeners
YAHOO.util.Event.on('uploadButton', 'click', uploader.carry);[/code]同样,我们也需要两个容器:
·imageContainer - 将包含我们上传的图片
·downloadLink - 将包含下载连接[code]<div id="imageContainer"></div>
<div id="downloadLink"></div>
[/code]两个容器事后将通过innerHTML更新

AJAX上传
对于AJAX的上传,请参见Code Central上的教程

强烈推荐此教程,我下载了示例代码,根据自己的需要改动了一点点,最后我搞了一个非常不错的JSON对象[uploader],它只有一个方法 carry。后者只是提交表单数据到一个指定的URL。[code]uploader = {
        carry: function(){
                // set form
                YAHOO.util.Connect.setForm('uploadForm', true);
                // upload image
                YAHOO.util.Connect.asyncRequest('POST', 'upload.php', {
                        upload: function(o){
                                // parse our json data
                                var jsonData = YAHOO.lang.JSON.parse(o.responseText);

                                // put image in our image container

                            
YAHOO.util.Dom.get('imageContainer').innerHTML = '<img id="yuiImg"
src="' + jsonData.image + '" width="' + jsonData.width + '" height="' +
jsonData.height + '" alt="" />';

                                // init our photoshop
                                photoshop.init(jsonData.image);

                                // get first cropped image
                                photoshop.getCroppedImage();
                        }
                });
        }
};
[/code]当上传完成,我们得到早前提到过的JSON数据。[code]{"image" : "images/myimage.jpg", "width" : "500", "height" : 400}
[/code]此数据和我们用来放置图片的容器imageContainer将以yuiImg作为id[code]YAHOO.util.Dom.get
('imageContainer').innerHTML = '<img id="yuiImg" src="' +
jsonData.image + '" width="' + jsonData.width + '" height="' +
jsonData.height + '" alt="" />';[/code]指定图片的长和宽是非常重要的,除非图片剪切工具工作不正常。
下面我们将实例化另一个JSON对象photoshop,我们一起来看看。

我们的photoshop对象[code]photoshop = {
        image: null,
        crop: null,

        init: function(image){
                // set our image
                photoshop.image = image;

                // our image cropper from the uploaded image
                photoshop.crop = new YAHOO.widget.ImageCropper('yuiImg');
                photoshop.crop.on('moveEvent', function() {
                        // get updated coordinates
                        photoshop.getCroppedImage();
                });
        },

        getCroppedImage: function(){
                var coordinates = photoshop.getCoordinates();

              var url = 'crop.php?image=' + photoshop.image +
'&cropStartX=' + coordinates.left +'&cropStartY=' +
coordinates.top +'&cropWidth=' + coordinates.width
+'&cropHeight=' + coordinates.height;
              
YAHOO.util.Dom.get('downloadLink').innerHTML = '<a href="' + url +
'">download cropped image</a>';               

        },

        getCoordinates: function(){
                return photoshop.crop.getCropCoords();
        }
};
[/code]这个初始化方法初始化了yuiImg[code]photoshop.crop = new
YAHOO.widget.ImageCropper('yuiImg');[/code]我们同样要声明moveEvent方法,每当这个图片被移动或是被调整大小,我们就调用getCroppedImage这个方法来更新下载连接。[code]photoshop.crop.on
('moveEvent', function() {
        // get updated coordinates
        photoshop.getCroppedImage();
});
[/code]getCroppedImage方法将生成裁减后的图片地址。在PHP里实现,我们需要
·要处理的图片
·X,Y轴的坐标
·裁减后的图片长和宽

幸运的是,YUI的剪切工具里有一个方法满足了我们的需要,它就是getCropCoords()方法。所以,无论什么时候调用getCroppedImage方法,我们取到剪切图片的坐标,然后生成一个下载连接。[code]// get coordinates
var coordinates = photoshop.getCoordinates();

// build our url
var
url = 'crop.php?image=' + photoshop.image + '&cropStartX=' +
coordinates.left +'&cropStartY=' + coordinates.top
+'&cropWidth=' + coordinates.width +'&cropHeight=' +
coordinates.height;

// put download link in our page
YAHOO.util.Dom.get('downloadLink').innerHTML = '<a href="' + url + '">download cropped image</a>';
[/code]index.php的所有内容就在这里了。

upload.php[code]
          if ($ext == "jpg") {
                      // generate unique file name
                  $newName = 'images/'.time().'.'.$ext;

                  // upload files
                if ((move_uploaded_file($_FILES['uploadImage']['tmp_name'], $newName))) {

                        // get height and width for image uploaded
                        list($width, $height) = getimagesize($newName);

                        // return json data
                           echo '{"image" : "'.$newName.'", "height" : "'.$height.'", "width" : "'.$width.'" }';
                }
                else {
                           echo '{"error" : "An error occurred while moving the files"}';
                }
          }
          else {
                     echo '{"error" : "Invalid image format"}';
          }
}
[/code]upload.php就像它写的那样,只解析jpg格式的图片,然后生成一个唯一的文件名,置于images的文件夹内,最后生成DOM可操作的JSON数据。当然images文件夹要设置为可读写。

crop.php[code]// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// force download nes image
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.$imgfile.'"');
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);
[/code]我们可以通过crop.php剪切上传的图片。首先我们得到所有的通过AJAX传递给我们的变量。[code]// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];
[/code]我们创建两个图片,原始图片和剪切了的图片,通过imagecopyresized方法来生成剪切图片。我们加入两个头部信息,一个告诉游览器这是一个图片,另一个是保存图片的对话框。

ajax +php 二级联动菜单代码
<script language="javascript" >
var http_request=false;
  function send_request(url){//初始化,指定处理函数,发送请求的函数
    http_request=false;
 //开始初始化XMLHttpRequest对象
 if(window.XMLHttpRequest){//Mozilla浏览器
  http_request=new XMLHttpRequest();
  if(http_request.overrideMimeType){//设置MIME类别
    http_request.overrideMimeType("text/xml");
  }
 }
 else if(window.ActiveXObject){//IE浏览器
  try{
   http_request=new ActiveXObject("Msxml2.XMLHttp");
  }catch(e){
   try{
   http_request=new ActiveXobject("Microsoft.XMLHttp");
   }catch(e){}
  }
    }
 if(!http_request){//异常,创建对象实例失败
  window.alert("创建XMLHttp对象失败!");
  return false;
 }
 http_request.onreadystatechange=processrequest;
 //确定发送请求方式,URL,及是否同步执行下段代码
    http_request.open("GET",url,true);
 http_request.send(null);
  }
  //处理返回信息的函数
  function processrequest(){
   if(http_request.readyState==4){//判断对象状态
     if(http_request.status==200){//信息已成功返回,开始处理信息
   document.getElementById(reobj).innerHTML=http_request.responseText;
  }
  else{//页面不正常
   alert("您所请求的页面不正常!");
  }
   }
  }
  function getclass(obj){
   var pid=document.form1.select1.value;
   document.getElementById(obj).innerHTML="<option>loading...</option>";
   send_request('doclass.php?pid='+pid);
   reobj=obj;
  }
 
</script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>ajax +php 二级联动菜单代码</title>
</head>

<body>
<form name="form1">
<select name="select1" id="class1" style="width:100;" onChange="getclass('class2');">
  <option selected="selected"></option>
  <option value="1">大类1</option>
  <option value="2">大类2</option>
</select>
<select name="select2"id="class2" style="width:100;">
</select>
</form>
</body>
</html>

php 处理代码

<?php

  header("Content-type: text/html;charset=GBK");//输出编码,避免中文乱码
  $pid=$_GET['pid'];

  $db=mysql_connect("localhost","root","7529639"); //创建数据库连接
  mysql_query("set names 'GBK'");
  mysql_select_db("menuclass");
  $sql="select classname from menu where parentid=".$pid."";
  $result=mysql_query($sql);
 
  //循环列出选项
  while($rows=mysql_fetch_array($result)){
   echo '<option>';
      echo $rows['classname'];
   echo "</option>n";
  }

?>

php 为图片加水印函数和缩略图的函数代码
/**
* 为图片加水印
* @param string $desImg 目标图片 参数格式为 ./images/pic.jpg
* @param string $waterImg 水印图片 参数格式同上,水印图片为 png格式,背景透明
* @param int positon 水印位置 1:顶部居左 2:顶部居右 3:居中 4 :底部居左 5:底部居右
* @param bool $saveas 是否另存为,默认值false,表示覆盖原图
* @param int $alpha 水印图片的不透明度
* @return string $savepath 新图片的路径
* **/
function watermark($desImg,$waterImg,$positon=1,$saveas=false,$alpha=30)
{
//获取目图片的基本信息
$temp=pathinfo($desImg);
$name=$temp["basename"];//文件名
$path=$temp["dirname"];//文件所在的文件夹
$extension=$temp["extension"];//文件扩展名
if($saveas)
{
//需要另存为
$name=rtrim($name,".$extension")."_2.";//重新命名
$savepath=$path."/".$name.$extension;
}
else
{
//不需要另存为则覆盖原图
$savepath=$path."/".$name;
}
$info=getImageInfo($desImg);//获取目标图片的信息
$info2=getImageInfo($waterImg);//获取水印图片的信息

$desImg=create($desImg);//从原图创建
$waterImg=create($waterImg);//从水印图片创建
//位置1:顶部居左
if($positon==1)
{
$x=0;
$y=0;
}
//位置2:顶部居右
if($positon==2)
{
$x=$info[0]-$info2[0];
$y=0;
}
//位置3:居中
if($positon==3)
{
$x=($info[0]-$info2[0])/2;
$y=($info[1]-$info2[1])/2;
}
//位置4:底部居左
if($positon==4)
{
$x=0;
$y=$info[1]-$info2[1];
}
//位置5:底部居右
if($positon==5)
{
$x=$info[0]-$info2[0];
$y=$info[1]-$info2[1];
}
imagecopymerge($desImg,$waterImg,$x,$y,0,0,$info2[0],$info2[1],$alpha);
imagejpeg($desImg,$savepath);
imagedestroy($desImg);
imagedestroy($waterImg);
return $savepath;
}
/**
* 获取图片的信息,width,height,image/type
* @param string $src 图片路径
* @return 数组
* **/
function getImageInfo($src)
{
return getimagesize($src);
}
/**
* 创建图片,返回资源类型
* @param string $src 图片路径
* @return resource $im 返回资源类型
* **/
function create($src)
{
$info=getImageInfo($src);
switch ($info[2])
{
case 1:
$im=imagecreatefromgif($src);
break;
case 2:
$im=imagecreatefromjpeg($src);
break;
case 3:
$im=imagecreatefrompng($src);
break;
}
return $im;
}
/**
* 缩略图主函数
* @param string $src 图片路径
* @param int $w 缩略图宽度
* @param int $h 缩略图高度
* @return mixed 返回缩略图路径
* **/

function resize($src,$w,$h)
{
$temp=pathinfo($src);
$name=$temp["basename"];//文件名
$dir=$temp["dirname"];//文件所在的文件夹
$extension=$temp["extension"];//文件扩展名
$savepath="{$dir}/{$name}.thumb.jpg";//缩略图保存路径,新的文件名为*.thumb.jpg

//获取图片的基本信息
$info=getImageInfo($src);
$width=$info[0];//获取图片宽度
$height=$info[1];//获取图片高度
$per1=round($width/$height,2);//计算原图长宽比
$per2=round($w/$h,2);//计算缩略图长宽比

//计算缩放比例
if($per1>$per2||$per1==$per2)
{
//原图长宽比大于或者等于缩略图长宽比,则按照宽度优先
$per=$w/$width;
}
if($per1<$per2)
{
//原图长宽比小于缩略图长宽比,则按照高度优先
$per=$h/$height;
}
$temp_w=intval($width*$per);//计算原图缩放后的宽度
$temp_h=intval($height*$per);//计算原图缩放后的高度
$temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布
$im=create($src);
imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);
if($per1>$per2)
{
imagejpeg($temp_img,$savepath);
return addBg($savepath,$w,$h,"w");
//宽度优先,在缩放之后高度不足的情况下补上背景
}
if($per1==$per2)
{
imagejpeg($temp_img,$savepath);
return $savepath;
//等比缩放
}
if($per1<$per2)
{
imagejpeg($temp_img,$savepath);

return addBg($savepath,$w,$h,"h");
//高度优先,在缩放之后宽度不足的情况下补上背景
}
}
/**
* 添加背景
* @param string $src 图片路径
* @param int $w 背景图像宽度
* @param int $h 背景图像高度
* @param String $first 决定图像最终位置的,w 宽度优先 h 高度优先 wh:等比
* @return 返回加上背景的图片
* **/
function addBg($src,$w,$h,$fisrt="w")
{
$bg=imagecreatetruecolor($w,$h);
$white = imagecolorallocate($bg,255,255,255);
imagefill($bg,0,0,$white);//填充背景

//获取目标图片信息
$info=getImageInfo($src);
$width=$info[0];//目标图片宽度
$height=$info[1];//目标图片高度
$img=create($src);
if($fisrt=="wh")
{
//等比缩放
return $src;
}
else
{
if($fisrt=="w")
{
$x=0;
$y=($h-$height)/2;//垂直居中
}
if($fisrt=="h")
{
$x=($w-$width)/2;//水平居中
$y=0;
}
imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);
imagejpeg($bg,$src);
imagedestroy($bg);
imagedestroy($img);
return $src;
}

}

php 生成条形码
<?php
function UPCAbarcode($code) {
  $lw = 2; $hi = 100;
  $Lencode = array('0001101','0011001','0010011','0111101','0100011',
                   '0110001','0101111','0111011','0110111','0001011');
  $Rencode = array('1110010','1100110','1101100','1000010','1011100',
                   '1001110','1010000','1000100','1001000','1110100');
  $ends = '101'; $center = '01010';
  /* UPC-A Must be 11 digits, we compute the checksum. */
  if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
  /* Compute the EAN-13 Checksum digit */
  $ncode = '0'.$code;
  $even = 0; $odd = 0;
  for ($x=0;$x<12;$x++) {
    if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
  }
  $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
  /* Create the bar encoding using a binary string */
  $bars=$ends;
  $bars.=$Lencode[$code[0]];
  for($x=1;$x<6;$x++) {
    $bars.=$Lencode[$code[$x]];
  }
  $bars.=$center;
  for($x=6;$x<12;$x++) {
    $bars.=$Rencode[$code[$x]];
  }
  $bars.=$ends;
  /* Generate the Barcode Image */
  $img = ImageCreate($lw*95+30,$hi+30);
  $fg = ImageColorAllocate($img, 0, 0, 0);
  $bg = ImageColorAllocate($img, 255, 255, 255);
  ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg);
  $shift=10;
  for ($x=0;$x<strlen($bars);$x++) {
    if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
    if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
    ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
  }
  /* Add the Human Readable Label */
  ImageString($img,4,5,$hi-5,$code[0],$fg);
  for ($x=0;$x<5;$x++) {
    ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
    ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
  }
  ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg);
  /* Output the Header and Content. */
  header("Content-Type: image/png");
  ImagePNG($img);
}
UPCAbarcode('47101496236');
?>

实现数据的导入导出,数据表结构的导入导出
********************************************************/

        //
        //包含Mysql数据库操作文件
        //
        require_once("MysqlDB.php");
        
/*******************************************************
**类    名:MysqlDB
**类 编 号:lcq-DB-003
**作    用:数据库链接的建立,数据操作,获取字段个数,记录条数等
**作    者:林超旗
**编写日期:(2007-04-07)
********************************************************/
class DBManagement implements IDBManagement
{        
        //
        //当前数据库中所有的数据表的名字
        //
        private $TablesName;
        //
        //默认路径
        //
        private $DefaultPath;
        //
        //当前要操作的数据库名
        //
        private $DatabaseName;
        //
        //操作数据库的对象
        //
        private $db;
        
/*******************************************************
**方 法 名:__construct
**功能描述:创建一个DBManagement的对象
**输入参数:$_DatabaseName-string<要操作的数据库名,如果为空则从配置文件中读取>
**        $_DefaultPath-string<存储数据的默认路径,如果为空则从配置文件中读取>
**输出参数:无
**返 回 值:无
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        function __construct($_DatabaseName="",$_DefaultPath="")//
        {
                require("config.inc.php");
                if(!$_DatabaseName)        {$this->DatabaseName=$dbName;}
                else {$this->DatabaseName=$_DatabaseName;}
               
                if(!$_DefaultPath) {$this->DefaultPath=$defaultPath;}
                else {$this->DefaultPath=$_DefaultPath;}
                $path=realpath($this->DefaultPath);
                $this->DefaultPath=str_replace("\","/",$path);
                //$this->db=new DBFactory();
                $this->db=new MysqlDB();
        }
        
/*******************************************************
**方 法 名:GetTablesName
**功能描述:获取$this->Database的所有数据表的名字
**输入参数:无         
**输出参数:无
**返 回 值:-array <$this->TablesName:$this->Database的所有数据表的名字>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function GetTablesName()
        {
                $result=$this->db->Query("show table status");
                while($Row=$this->db->NextRecord($result))
                {
                        $this->TablesName[]=$Row["Name"];
                }
                return $this->TablesName;
        }
        
/*******************************************************
**方 法 名:GetDataFileName
**功能描述:获取与$this->Database的所有数据表对应的数据文件的物理文件名
**输入参数:无         
**输出参数:无
**返 回 值:-array <$DataFilesName:$与$this->Database的所有数据表对应的数据文件的物理文件名>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function GetDataFileName()
        {
                $this->GetTablesName();
                $count=count($this->GetTablesName());
                for ($i=0;$i<$count;$i++)
                {
                        $DataFilesName[]=$this->DefaultPath."/".$this->TablesName[$i].".txt";
                        //echo $DataFilesName[$i];
                }
                return $DataFilesName;
        }
        
/*******************************************************
**方 法 名:SaveTableStructure
**功能描述:保存数据表的结构到install.sql文件中,目标路径为$DefaultPath
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示保存成功;
**                为false表示保存失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function SaveTableStructure($text)
        {
                $fileName=$this->DefaultPath."/Install.sql";
                //if(file_exists($fileName))
                //{
                //        unlink($fileName);
                //}
                //echo $text;
                $fp=fopen($fileName,"w+");
                fwrite($fp,$text);
        }
        
/*******************************************************
**方 法 名:RestoreTableStructure
**功能描述:备份$this->Database中所有数据表的结构
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的结构备份成功;
**                为false表示全部或部分数据表的结构备份失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function BackupTableStructure()
        {
                $i=0;
                $sqlText="";
               
                $this->GetTablesName();
                $count=count($this->TablesName);
                //
                //取出所有数据表的结构
                //
                while($i<$count)
                {
                        $tableName=$this->TablesName[$i];        
                        $result=$this->db->Query("show create table $tableName");
                        $this->db->NextRecord($result);
                        //
                        //取出成生表的SQL语句
                        //
                        $sqlText.="DROP TABLE IF EXISTS `".$tableName."`; ";//`
                        $sqlText.=$this->db->GetField(1)."; ";
                        $i++;
                }
                $sqlText=str_replace("r","",$sqlText);
                $sqlText=str_replace("n","",$sqlText);
                //$sqlText=str_replace("'","`",$sqlText);
                $this->SaveTableStructure($sqlText);
        }

/*******************************************************
**方 法 名:RestoreTableStructure
**功能描述:还原$this->Database中所有数据表的结构
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的结构还原成功;
**                为false表示全部或部分数据表的结构还原失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function RestoreTableStructure()
        {
                $fileName=$this->DefaultPath."/Install.sql";
                if(!file_exists($fileName)){echo "找不到表结构文件,请确认你以前做过备份!";exit;}
                $fp=fopen($fileName,"r");
               
                $sqlText=fread($fp,filesize($fileName));
                //$sqlText=str_replace("r","",$sqlText);
                //$sqlText=str_replace("n","",$sqlText);               
                $sqlArray=explode("; ",$sqlText);
                try
                {
                        $count=count($sqlArray);
                        //
                        //数组的最后一个为";",是一个无用的语句,
                        //
                        for($i=1;$i<$count;$i++)
                        {
                                $sql=$sqlArray[$i-1].";";
                                $result=$this->db->ExecuteSQL($sql);
                                if(!mysql_errno())
                                {
                                        if($i%2==0){echo "数据表".($i/2)."的结构恢复成功!n";}
                                }
                                else
                                {
                                        if($i%2==0)
                                        {
                                                echo "数据表".($i/2)."的结构恢复失败!n";
                                                exit();
                                        }
                                }
                        }
                }
                catch(Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        $this->db->Close();
                        return false;
                }
        }
        
/*******************************************************
**方 法 名:ImportData
**功能描述:导入$this->Database中所有数据表的数据从与其同名的.txt文件中,源路径为$DefaultPath
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据导入成功;
**                为false表示全部或部分数据表的数据导入失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/
        function ImportData()
        {
                $DataFilesName=$this->GetDataFileName();
                $count=count($this->TablesName);
                //$this->db->ExecuteSQL("set character set gbk");
                for ($i=0;$i<$count;$i++)
                {
                        //$DataFilesName[$i]=str_replace("\","/",$DataFilesName[$i])
                        //echo $DataFilesName[$i];
                        $sqlLoadData="load data infile '".$DataFilesName[$i]."'  into table ".$this->TablesName[$i];
                        $sqlCleanData="delete from ".$this->TablesName[$i];
                        //echo $sql."n";
                        try
                        {
                                //$this->db->ExecuteSQL("set character set utf8");
                                //$this->db->ExecuteSQL("SET NAMES 'utf8'");
                                $this->db->ExecuteSQL($sqlCleanData);
                                $this->db->ExecuteSQL($sqlLoadData);
                                return true;
                                //echo "数据导入成功!";
                        }
                        catch (Exception $e)
                        {
                                $this->db->ShowError($e->getMessage());
                                return false;
                                exit();
                        }
                }        
        }
        
/*******************************************************
**方 法 名:ExportData
**功能描述:导出$this->Database中所有数据表的数据到与其同名的.txt文件中,目标路径为$DefaultPath
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据导出成功;
**                为false表示全部或部分数据表的数据导出失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/
        function ExportData()
        {
                $DataFilesName=$this->GetDataFileName();
                $count=count($this->TablesName);
                try
                {
                        for ($i=0;$i<$count;$i++)
                        {
                                $sql="select * from ".$this->TablesName[$i]."  into outfile '".$DataFilesName[$i]."'";
                                if(file_exists($DataFilesName[$i]))
                                {
                                        unlink($DataFilesName[$i]);
                                }
                                //$this->db->ExecuteSQL("SET NAMES 'utf8'");
                                $this->db->ExecuteSQL($sql);
                        }
                        return true;
                        //echo "数据导出成功!";
                }
                catch (Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        return false;
                        exit();
                }
        }
        
/*******************************************************
**方 法 名:BackupDatabase
**功能描述:备份$this->Database中所有数据表的结构和数据
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据库备份成功;
**                为false表示全部或部分数据表的数据库备份失败>
**作    者:林超旗
**日    期:2007-04-10
**修 改 人:
**日    期:
********************************************************/        
        function BackupDatabase()
        {
                try
                {
                        $this->BackupTableStructure();
                        $this->ExportData();
                        return true;
                }
                catch (Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        return false;
                        exit();
                }
        }
        
/*******************************************************
**方 法 名:RestoreDatabase
**功能描述:还原$this->Database中所有数据表的结构和数据
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据库还原成功;
**                为false表示全部或部分数据表的数据库还原失败>
**作    者:林超旗
**日    期:2007-04-10
**修 改 人:
**日    期:
********************************************************/        
        function RestoreDatabase()
        {
                try
                {
                        $this->RestoreTableStructure();
                        $this->ImportData();
                        return true;
                }
                catch (Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        return false;
                        exit();
                }               
        }
}
?>[/php]

[!--infotagslink--]

相关文章

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • Photoshop古装美女图片转为工笔画效果制作教程

    今天小编在这里就来给各位Photoshop的这一款软件的使用者们来说说把古装美女图片转为细腻的工笔画效果的制作教程,各位想知道方法的使用者们,那么下面就快来跟着小编一...2016-09-14
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮

    jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮...2013-10-13
  • 利用JS实现点击按钮后图片自动切换的简单方法

    下面小编就为大家带来一篇利用JS实现点击按钮后图片自动切换的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-25
  • Photoshop枪战电影海报图片制作教程

    Photoshop的这一款软件小编相信很多的人都已经是使用过了吧,那么今天小编在这里就给大家带来了用Photoshop软件制作枪战电影海报的教程,想知道制作步骤的玩家们,那么下面...2016-09-14
  • python opencv通过4坐标剪裁图片

    图片剪裁是常用的方法,那么如何通过4坐标剪裁图片,本文就详细的来介绍一下,感兴趣的小伙伴们可以参考一下...2021-06-04
  • 使用PHP下载CSS文件中的图片的代码

    共享一段使用PHP下载CSS文件中的图片的代码 复制代码 代码如下: <?php //note 设置PHP超时时间 set_time_limit(0); //note 取得样式文件内容 $styleFileContent = file_get_contents('images/style.css'); //not...2013-10-04
  • PHP swfupload图片上传的实例代码

    PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
  • C#中图片旋转和翻转(RotateFlipType)用法分析

    这篇文章主要介绍了C#中图片旋转和翻转(RotateFlipType)用法,实例分析了C#图片旋转及翻转Image.RotateFlip方法属性的常用设置技巧,需要的朋友可以参考下...2020-06-25
  • OpenCV如何去除图片中的阴影的实现

    这篇文章主要介绍了OpenCV如何去除图片中的阴影的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-29
  • js实现上传图片及时预览

    这篇文章主要为大家详细介绍了js实现上传图片及时预览的相关资料,具有一定的参考价值,感兴趣的朋友可以参考一下...2016-05-09
  • ps怎么制作图片阴影效果

    ps软件是现在很多人比较喜欢的,有着非常不错的使用效果,这次文章就给大家介绍下ps怎么制作图片阴影效果,还不知道制作方法的赶紧来看看。 ps图片阴影效果怎么做方法/...2017-07-06
  • C#将图片和字节流互相转换并显示到页面上

    本文主要介绍用C#实现图片转换成字节流,字节流转换成图片,并根据图片路径返回图片的字节流,有需要的朋友可以参考下...2020-06-25
  • 微信小程序如何获取图片宽度与高度

    这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • JavaScript 如何禁止用户保存图片

    这篇文章主要介绍了JavaScript 如何禁止用户保存图片,帮助大家完成需求,更好的理解和使用JavaScript,感兴趣的朋友可以了解下...2020-11-19
  • 百度编辑器ueditor修改图片上传默认路径

    本案例非通用,仅作笔记以备用 修改后的结果是 百度编辑器里上传的图片路径为/d/file/upload1...2014-07-03
  • php上传图片学习笔记与心得

    我们在php中上传文件就必须使用#_FILE变量了,这个自动全局变量 $_FILES 从 PHP 4.1.0 版本开始被支持。在这之前,从 4.0.0 版本开始,PHP 支持 $HTTP_POST_FILES 数组。这...2016-11-25