菜单

ajax上污染图片及PHP并减少图片显示的章程

2018年11月17日 - Ajax

本文实例为大家大快朵颐了ajax上污染图片及PHP并缩减图片显示的现实代码,供大家参考,具体内容如下

本文实例讲解了PHP图片及传并压缩的实现方式,分享给大家供大家参考,具体内容如下

需就是,上传图片并压缩图片页面效果使下图:

运及三只文本

图片 1

HTML代码

老三单文本代码如下:
连年数据库:**connect.php
**

<div id="main"> 
 <div class="demo"> 
  <div class="btn btn-success"> 
   上传图片 
   <input id="fileupload" type="file" name="mypic"> 
  </div> 
  <!--加载进度--> 
  <div class="progress progress-striped"> 

   0% 
  </div> 
  <!--显示图片--> 
  <div id="showimg"></div> 
  <!--删除图片--> 
  <div class="files"></div> 
 </div> 
</div> 
<?php
$db_host = '';
$db_user = '';
$db_psw = '';
$db_name = '';
$db_port = '';
$sqlconn=new mysqli($db_host,$db_user,$db_psw,$db_name);
$q="set names utf8;";
$result=$sqlconn->query($q);
if (mysqli_connect_errno()) {
 printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
}
?>

CSS代码和引入的bootstrap

执行SQL语句:test_upload.php

<style type="text/css"> 
 .demo{width:580px; margin:30px auto} 
 .btn{position: relative;overflow: hidden;margin-right: 4px;} 
 .btn input {position: absolute;top: 0; right: 0;margin: 0;border: solid transparent;opacity: 0;filter:alpha(opacity=0);} 
 .progress { position:relative; margin-left:100px; margin-top:-24px; width:200px; border-radius:3px; display:none} 
 .percent { position:absolute; top:1px; left:2%; color:#fff } 
 .files{margin:10px 0} 
 .delimg{margin-left:20px; color:#090; cursor:pointer;margin-top: -6px;} 
</style> 
<!--bootstrap.css3.3.7--> 
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
<?php
require ("connect.php");
require ("upload_img.php");
$real_img=$uploadfile; 
$small_img=$uploadfile_resize;
$insert_sql = "insert into img (real_img,small_img) values (?,?)";
$result = $sqlconn -> prepare($insert_sql);
$result -> bind_param("ss", $real_img,$small_img);
$result -> execute();
?>

JS代码

上传图片并缩减:upload_img.php

<!--jquery1.8.1--> 
 <script src="http://code.jquery.com/jquery-1.8.1.min.js"></script> 
 <!--图片jquery.form.js--> 
 <script type="text/javascript" src="https://www.helloweba.net/demo/upload/jquery.form.js"></script> 
<script type="text/javascript"> 
 $(function () { 
  //进度条百分比加载颜色 
  var bar = $('.bar'); 
  //进度条百分比 
  var percent = $('.percent'); 
  //图片显示 
  var showimg = $('#showimg'); 
  //进度条 
  var progress = $(".progress"); 
  //新增 
  var files = $(".files"); 
  var btn = $(".btn span"); 
  $(".demo").wrap("<form id='myupload' action='action.php' method='post' enctype='multipart/form-data'></form>"); 
  //点击上传图片 
  $("#fileupload").change(function(){ 
   //提交表单 
   $("#myupload").ajaxSubmit({ 
    dataType: 'json', 
    beforeSend: function() { 

     //显示进度条 
     progress.show(); 
     //进度条为0 
     var percentVal = '0%'; 
     bar.width(percentVal); 
     percent.html(percentVal); 
     btn.html("上传中..."); 
    }, 
    //上传进度 
    uploadProgress: function(event, position, total, percentComplete) { 
     //进度条加载长度数据是number型 
     var percentVal = percentComplete + '%'; 
     bar.width(percentVal) 
     percent.html(percentVal); 
    }, 
    success: function(data) { 
     //上传成功返回参数 
     files.html("<b>"+data.name+"("+data.size+"k)</b> 删除"); 
     showimg.html("<img src='"+data.pic+"'>"); 
     btn.html("上传图片"); 
    }, 
    error:function(xhr){ 
     //上传失败 
     btn.html("上传失败"); 
     bar.width('0') 
     files.html(xhr.responseText); 
    }, 
    clearForm: true 
   }); 
  }); 

  //删除图片js 
  $(".delimg").live('click',function(){ 
   //获取图片地址 
   var pic = $(this).attr("rel"); 
   $.post("action.php?act=delimg",{imagename:pic},function(msg){ 
    if(msg=='delete'){ 
     files.html("删除成功."); 
     //删除图片效果 
     showimg.empty(); 
     //隐藏进度条 
     progress.hide(); 
    }else{ 
     alert(msg); 
    } 
   }); 
  }); 
 }); 
</script> 
<?php 
//设置文件保存目录
$uploaddir = "upfiles/"; 
//设置允许上传文件的类型
$type=array("jpg","gif","bmp","jpeg","png"); 

//获取文件后缀名函数 
function fileext($filename) 
{ 
 return substr(strrchr($filename, '.'), 1); 
} 

//生成随机文件名函数 
function random($length) 
{ 
 $hash = 'CR-'; 
 $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; 
 $max = strlen($chars) - 1; 
 mt_srand((double)microtime() * 1000000); 
 for($i = 0; $i < $length; $i++) 
 { 
  $hash .= $chars[mt_rand(0, $max)]; 
 } 
 return $hash; 
} 

$a=strtolower(fileext($_FILES['filename']['name'])); 

//判断文件类型 
if(!in_array(strtolower(fileext($_FILES['filename']['name'])),$type)) 
{ 
 $text=implode(",",$type); 
 $ret_code=3;//文件类型错误
 $page_result=$text;
 $retArray = array('ret_code' => $ret_code,'page_result'=>$page_result);
 $retJson = json_encode($retArray);
 echo $retJson;
 return;
} 

//生成目标文件的文件名 
else
{ 
 $filename=explode(".",$_FILES['filename']['name']); 
 do 
 { 
  $filename[0]=random(10); //设置随机数长度 
  $name=implode(".",$filename); 
  //$name1=$name.".Mcncc"; 
  $uploadfile=$uploaddir.$name; 
 } 

 while(file_exists($uploadfile)); 

 if (move_uploaded_file($_FILES['filename']['tmp_name'],$uploadfile)) 
 { 
  if(is_uploaded_file($_FILES['filename']['tmp_name'])) 
  {
   $ret_code=1;//上传失败
  } 
 else 
 {//上传成功
  $ret_code=0;
 } 
 } 
$retArray = array('ret_code' => $ret_code);
$retJson = json_encode($retArray);
echo $retJson;
}

//压缩图片

$uploaddir_resize="upfiles_resize/";
$uploadfile_resize=$uploaddir_resize.$name;

//$pic_width_max=120;
//$pic_height_max=90;
//以上与下面段注释可以联合使用,可以使图片根据计算出来的比例压缩

$file_type=$_FILES["filename"]['type'];

function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)
{
 //取得当前图片大小
 $width = imagesx($uploadfile);
 $height = imagesy($uploadfile);
 $i=0.5;
 //生成缩略图的大小
 if(($width > $maxwidth) || ($height > $maxheight))
 {
  /*
  $widthratio = $maxwidth/$width;
  $heightratio = $maxheight/$height;

  if($widthratio < $heightratio)
  {
   $ratio = $widthratio;
  }
  else
  {
    $ratio = $heightratio;
  }

  $newwidth = $width * $ratio;
  $newheight = $height * $ratio;
  */
  $newwidth = $width * $i;
  $newheight = $height * $i;
  if(function_exists("imagecopyresampled"))
  {
   $uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);
   imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  }
  else
  {
   $uploaddir_resize = imagecreate($newwidth, $newheight);
   imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  }

  ImageJpeg ($uploaddir_resize,$name);
  ImageDestroy ($uploaddir_resize);
 }
 else
 {
  ImageJpeg ($uploadfile,$name);
 }
}



if($_FILES["filename"]['size'])
{
 if($file_type == "image/pjpeg"||$file_type == "image/jpg"|$file_type == "image/jpeg")
 {
  //$im = imagecreatefromjpeg($_FILES[$upload_input_name]['tmp_name']);
  $im = imagecreatefromjpeg($uploadfile);
 }
 elseif($file_type == "image/x-png")
 {
  //$im = imagecreatefrompng($_FILES[$upload_input_name]['tmp_name']);
  $im = imagecreatefromjpeg($uploadfile);
 }
 elseif($file_type == "image/gif")
 {
  //$im = imagecreatefromgif($_FILES[$upload_input_name]['tmp_name']);
  $im = imagecreatefromjpeg($uploadfile);
 }
 else//默认jpg
 {
  $im = imagecreatefromjpeg($uploadfile);
 }
 if($im)
 {
  ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);

  ImageDestroy ($im);
 }
} 
?>

PHP代码

央遵现实情况更改connect.php,test_upload.php中对应之信息。

<?php 
date_default_timezone_set("PRC"); 
//引入图片压缩类 
require 'imgcompress.class.php'; 
//如果有数据就是当前数据,没有为空 
$action=isset($_GET['act']) ? $action = $_GET['act']:''; 
$filename=isset($_POST['imagename']) ? $_POST['imagename']:''; 

if($action=='delimg'){ 

 if(!empty($filename)){ 
  //删除图片 
  unlink($filename); 
  //向页面回调参数 
  echo 'delete'; 
 }else{ 
  echo '删除失败.'; 
 } 
 }else{ 
 //获取图片名字和原数据 
 $picname = $_FILES['mypic']['name']; 
 //获取图片大小 
 $picsize = $_FILES['mypic']['size']; 


 if ($picname != "") { 

  /** 
   * 
   * 注释代码为是否限制用户上传图片大小和用户上传文件格式 
   */ 
//  if ($picsize > 512000) { //限制上传大小 
//   echo '图片大小不能超过500k'; 
//   exit; 
//  } 
//  $type = strstr($picname, '.'); //限制上传格式 
//   if ($type != ".gif" && $type != ".jpg") { 
//       echo '图片格式不对!'; 
//    exit; 
//   } 
//  $rand = rand(100, 999); 
//  $pics = date("YmdHis") . $rand . $type; //命名图片名称 

  //防止上传图片名中文乱码 
  $name=iconv("UTF-8","gb2312", $picname); 
  //上传路径 
  $pic_path = "files/". $name; 
  //移动图片位置 
  move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path); 
 } 
 //图片地址 拿到图片地址可以传递到数据库 
 $source = "files/". $picname; 
 $size = round($picsize/1024,2); //转换成kb 
 $arr = array( 
  'name'=>$picname, 
  'pic'=>$source, 
  'size'=>$size 
 ); 
 echo json_encode($arr); //输出json数据 


 $dst_img = $picname; 
 $percent = 1; //原图压缩,不缩放 
 /** 
  * 方法一 
  * 压缩图片传递三个参数 
  * 1.资源文件 
  * 2.压缩图片质量 1是最高,从0.1开始 
  * 3.图片压缩名字 
  */ 
 (new Compress($source,$percent))->compressImg($dst_img); 

 /** 
  * 方法二 
  * 1.资源文件 
  * 2.压缩图片质量 
  * 3.图片名字 
  */ 
// require 'image.class.php'; 
// $src = "001.jpg"; 
// $image = new Image($src);·············· 
// $image->percent = 0.2; 
// $image->saveImage(md5("aa123")); 
} 

如上就是是PHP实现图片及传并压缩的方式,希望对大家的学习php程序设计具有助

图形压缩类请下载源码

乃或许感兴趣之稿子:

如上就是是本文的全部内容,希望对大家之修抱有帮助,也希望大家多支持脚本的寒。

而或许感兴趣的篇章:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图