php 生成条形码

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

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');
?>

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;
}

}

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

        //
        //包含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]

已测(表结构:id 表ID(唯一)title 各类标题flid 类别的ID (大类为1 中类为2 小类为3)pid 上类的ID(大类就跟大类,提交中类的时候这地方写大类的ID,提交小类的时候写中类的ID) )

<?php   $link=mysql_connect("localhost","root","root") or die("数据库服务器连接错误".mysql_error());   mysql_select_db("sanji",$link) or die("数据库访问错误".mysql_error());   mysql_query("set character set gb2312");     mysql_query("set names gb2312");?><html><head><title>下拉框连动</title></head><body><script language="JavaScript"><!--var subcat = new Array();<?$i=0;$sql="select * from sanji where flid=2";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "subcat[".$i++."] = new Array('".$arr["pid"]."','".$arr["title"]."','".$arr["id"]."');n";}?>var subcat2 = new Array();<?$i=0;$sql="select * from sanji where flid=3";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "subcat2[".$i++."] = new Array('".$arr["pid"]."','".$arr["title"]."','".$arr["id"]."');n";}?>function changeselect1(locationid){document.form1.s2.length = 0;document.form1.s2.options[0] = new Option('==请选择==','');for (i=0; i<subcat.length; i++){if (subcat[i][0] == locationid){document.form1.s2.options[document.form1.s2.length] = new Option(subcat[i][1], subcat[i][2]);}}}function changeselect2(locationid){document.form1.s3.length = 0;document.form1.s3.options[0] = new Option('==请选择==','');for (i=0; i<subcat2.length; i++){if (subcat2[i][0] == locationid){document.form1.s3.options[document.form1.s3.length] = new Option(subcat2[i][1], subcat2[i][2]);}}}//--></script>三级联动:<BR><form name="form1"><select name="s1" onChange="changeselect1(this.value)"><option>==请选择==</option><?$sql="select * from sanji where flid=1";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "<option value=".$arr["id"].">".$arr["title"]."</option>n";}?></select><select name="s2" onChange="changeselect2(this.value)"><option>==请选择==</option></select><select name="s3" onChange="alert('选选择'+this.value)"><option>==请选择==</option></select></form><BR></body></html>

数据库叫"sanji"-- phpMyAdmin SQL Dump-- version 2.11.4-- http://www.phpmyadmin.net---- 主机: localhost-- 生成日期: 2009 年 11 月 03 日 15:12-- 服务器版本: 5.0.51-- PHP 版本: 5.2.5SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";---- 数据库: `sanji`---- ------------------------------------------------------------ 表的结构 `sanji`--CREATE TABLE IF NOT EXISTS `sanji` (  `id` int(10) NOT NULL auto_increment,  `title` varchar(30) collate utf8_unicode_ci NOT NULL,  `flid` int(10) NOT NULL,  `pid` int(10) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;---- 导出表中的数据 `sanji`--INSERT INTO `sanji` (`id`, `title`, `flid`, `pid`) VALUES(1, '我是1', 1, 1),(2, '我是2,归1管', 2, 1),(3, '我是3,归2管', 3, 2),(4, '我是4,也归2管', 3, 2);

if( isset($_FILES['upImg']) )
{
 if( $userGroup[$loginArr['group']]['upload'] == 0 )
 {
  echo '{"error":"您所在的用户组无权上传图片!"}';
 }
 else
 {
  $savePath = "attachment/img/".date('Y/m/d/H');

  mkDirs($savePath);

  $fileType = strtolower(strrchr($_FILES['upImg']['name'],"."));

  if ( !in_array($fileType, array(".jpg",".jpeg",".gif",".png")) )
  {
   echo '{"error":"目前仅支持格式为jpg、jpeg、gif、png的图片!"}';
  }
  elseif( $_FILES['upImg']['size'] > 204800 )
  {
   echo '{"error":"图片不能超过200K!"}';
  }
  else
  {
   $saveImg = $savePath."/".$loginArr['uid']."_".time().rand().$fileType;

   if( @move_uploaded_file($_FILES['upImg']['tmp_name'], $saveImg) )
   {
    echo '{"error":"","msg":"http://'.$site_domain.$site_catalog.$saveImg.'"}';
   }
   else
   {
    echo '{"error":"图片上传失败!"}';
   }
  }
 }
}

if( $loginArr['state'] == 0 )
{
 echo '{"error":"您还没有登录!"}';
}
else
{
 $avatarPath = "attachment/avatar/".($loginArr['uid']%32)."/".($loginArr['uid']%257)."/".$loginArr['uid'];

 if( isset($_FILES['upAvatar']) )
 {
  mkDirs($avatarPath);

  $fileType = strtolower(strrchr($_FILES['upAvatar']['name'],"."));

  if ( !in_array($fileType, array(".jpg",".jpeg",".gif",".png")) )
  {
   echo '{"error":"目前仅支持格式为jpg、jpeg、gif、png的图片!"}';
  }
  elseif( $_FILES['upAvatar']['size'] > 2097152 )
  {
   echo '{"error":"图片不能超过2MB!"}';
  }
  else
  {
   $imgInfo = @getimagesize($_FILES['upAvatar']['tmp_name']);

   if( !$imgInfo || !in_array($imgInfo[2], array(1,2,3)) )
   {
    echo '{"error":"系统无法识别您上传的文件!"}';
   }
   else
   {
    $TmpAvatar = $avatarPath."/temp".$fileType;
    
    if( @move_uploaded_file($_FILES['upAvatar']['tmp_name'], $TmpAvatar) )
    {
     $maxWidth = 520;

     $maxHeight = 520;

     if( $maxWidth > $imgInfo[0] || $maxHeight > $imgInfo[1] )
     {
      $maxWidth = $imgInfo[0];

      $maxHeight = $imgInfo[1];
     }
     else
     {
      if ( $imgInfo[0] < $imgInfo[1] )
       $maxWidth = ($maxHeight / $imgInfo[1]) * $imgInfo[0];
      else
       $maxHeight = ($maxWidth / $imgInfo[0]) * $imgInfo[1];
     }

     if( $maxWidth < 40 )
     {
      $maxWidth = 40;
     }

     if( $maxHeight < 40 )
     {
      $maxHeight = 40;
     }

     $image_p = imagecreatetruecolor($maxWidth, $maxHeight);

     switch($imgInfo[2])
     {
      case 1:
       $image = imagecreatefromgif($TmpAvatar);
       break;
      case 2:
       $image = imagecreatefromjpeg($TmpAvatar);
       break;
      case 3:
       $image = imagecreatefrompng($TmpAvatar);
       break;
     }

     imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $imgInfo[0], $imgInfo[1]);

     imagejpeg($image_p, $avatarPath."/temp.jpg",100);

     imagedestroy($image_p);

     imagedestroy($image);

     if( $fileType != ".jpg" && file_exists($TmpAvatar) )
     {
      unlink($TmpAvatar);
     }

     echo '{"error":"","url":"'.$avatarPath.'/temp.jpg?'.rand().'","width":"'.$maxWidth.'","height":"'.$maxHeight.'"}';
    }
    else
    {
     echo '{"error":"图片上传失败!"}';
    }
   }
  }
 }

 if( isset($_POST['x'],$_POST['y'],$_POST['w'],$_POST['h']) )
 {
  if( is_numeric($_POST['x']) && is_numeric($_POST['y']) && $_POST['w'] > 0 && $_POST['h'] > 0 )
  {
   $image_p = imagecreatetruecolor(40, 40);

   $image = imagecreatefromjpeg($avatarPath."/temp.jpg");

   imagecopyresampled($image_p, $image, 0, 0, $_POST['x'], $_POST['y'], 40, 40, $_POST['w'], $_POST['h']);

   imagejpeg($image_p, $avatarPath."/40_40.jpg",100);

   imagedestroy($image_p);

   imagedestroy($image);

   unlink($avatarPath."/temp.jpg");

   echo "1";
  }
 }

 if( isset($_POST['avatar']) && $_POST['avatar'] == "delete" )
 {
  if( file_exists($avatarPath."/temp.jpg") )
  {
   unlink($avatarPath."/temp.jpg");
  }
 }
}

ob_end_flush();

[!--infotagslink--]

相关文章

  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • php中去除文字内容中所有html代码

    PHP去除html、css样式、js格式的方法很多,但发现,它们基本都有一个弊端:空格往往清除不了 经过不断的研究,最终找到了一个理想的去除html包括空格css样式、js 的PHP函数。...2013-08-02
  • index.php怎么打开?如何打开index.php?

    index.php怎么打开?初学者可能不知道如何打开index.php,不会的同学可以参考一下本篇教程 打开编辑:右键->打开方式->经文本方式打开打开运行:首先你要有个支持运行PH...2017-07-06
  • php二维码生成

    本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
  • Java生成随机姓名、性别和年龄的实现示例

    这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
  • C#生成随机数功能示例

    这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • PHP中func_get_args(),func_get_arg(),func_num_args()的区别

    复制代码 代码如下:<?php function jb51(){ print_r(func_get_args()); echo "<br>"; echo func_get_arg(1); echo "<br>"; echo func_num_args(); } jb51("www","j...2013-10-04
  • php生成唯一数字id的方法汇总

    关于生成唯一数字ID的问题,是不是需要使用rand生成一个随机数,然后去数据库查询是否有这个数呢?感觉这样的话有点费时间,有没有其他方法呢?当然不是,其实有两种方法可以解决。 1. 如果你只用php而不用数据库的话,那时间戳+随...2015-11-24
  • PHP编程 SSO详细介绍及简单实例

    这篇文章主要介绍了PHP编程 SSO详细介绍及简单实例的相关资料,这里介绍了三种模式跨子域单点登陆、完全跨单点域登陆、站群共享身份认证,需要的朋友可以参考下...2017-01-25
  • jQuery为动态生成的select元素添加事件的方法

    下面小编就为大家带来一篇jQuery为动态生成的select元素添加事件的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-09-01
  • PHP自动生成后台导航网址的最佳方法

    经常制作开发不同的网站的后台,写过很多种不同的后台导航写法。 最终积累了这种最写法,算是最好的吧...2013-09-29
  • PHP实现创建以太坊钱包转账等功能

    这篇文章主要介绍了PHP实现创建以太坊钱包转账等功能,对以太坊感兴趣的同学,可以参考下...2021-04-20
  • php微信公众账号开发之五个坑(二)

    这篇文章主要为大家详细介绍了php微信公众账号开发之五个坑,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2016-10-02
  • ThinkPHP使用心得分享-ThinkPHP + Ajax 实现2级联动下拉菜单

    首先是数据库的设计。分类表叫cate.我做的是分类数据的二级联动,数据需要的字段有:id,name(中文名),pid(父id). 父id的设置: 若数据没有上一级,则父id为0,若有上级,则父id为上一级的id。数据库有内容后,就可以开始写代码,进...2014-05-31
  • PHP如何通过date() 函数格式化显示时间

    这篇文章主要介绍了PHP如何通过date() 函数格式化显示时间,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-11-13
  • js生成随机数的方法实例

    js生成随机数主要用到了内置的Math对象的random()方法。用法如:Math.random()。它返回的是一个 0 ~ 1 之间的随机数。有了这么一个方法,那生成任意随机数就好理解了。比如实际中我们可能会有如下的需要: (1)生成一个 0 - 1...2015-10-21
  • PHP+jQuery+Ajax实现多图片上传效果

    今天我给大家分享的是在不刷新页面的前提下,使用PHP+jQuery+Ajax实现多图片上传的效果。用户只需要点击选择要上传的图片,然后图片自动上传到服务器上并展示在页面上。...2015-03-15
  • PHP验证码生成与验证例子

    验证码是一个现在WEB2.0中常见的一个功能了,像注册、登录又或者是留言页面,都需要注册码来验证当前操作者的合法性,我们会看到有些网站没有验证码,但那是更高级的验证了,...2016-11-25
  • PHP生成不同颜色、不同大小的tag标签函数

    复制代码 代码如下:function getTagStyle(){ $minFontSize=8; //最小字体大小,可根据需要自行更改 $maxFontSize=18; //最大字体大小,可根据需要自行更改 return 'font-size:'.($minFontSize+lcg_value()*(abs($maxFo...2013-10-04
  • JS生成某个范围的随机数【四种情况详解】

    下面小编就为大家带来一篇JS生成某个范围的随机数【四种情况详解】。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧...2016-04-22