Home Article html(前端)+php(后端)实现图片上传并且优化压缩...

html(前端)+php(后端)实现图片上传并且优化压缩图片体积源码展示

Release time:2018-08-16 07:35:24 Author:小键键 Reading volume:469

html页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<head>
	<title> demo</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
      <link rel="stylesheet" href="https://css.letvcdn.com/lc04_yinyue/201612/19/20/00/bootstrap.min.css">
  <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
  <link rel="icon" href="//www.71idc.cn/favicon.ico"  type="image/x-icon">
  <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
      <style>
      img{ pointer-events: none; }
           </style>
       <script>
      function clickfile()
  {
  document.getElementById('file').click()
    return false;
  }
     
         </script>
  <div class="container" style="padding-top:70px;">
    <div class="col-xs-12 col-sm-10 col-lg-8 center-block" style="float: none;">
      <div class="panel panel-primary">
        <div class="panel-body">
      <div class="col-xs-12 col-sm-10 col-lg-8 center-block" style="float: none;">
        <center>
          <div class="form-group" id="jia_pic"  style="width:200px; height:200px; background:url('images/upload.jpg');" onclick="clickfile();">
          
  </div>
            <img id="myimage" height="200" width="200"  src="images/upload.jpg" style="display: none;"/>
	<div class="form-group"  id="picture" style="display: none;">
  
      <br/>
                	<p><input id="file" type="file" name="file" class="btn btn-default" accept="image/gif, image/png, image/jpg, image/jpeg" style="visi">上传图片</p>
                    <p id="log"></p>
       

                </div>
                     <br/> <a href="javascript:void(0);" onclick="clickfile()" class="uploadbtn">点击上传文件</a>

           </center>
        </div>
      </div>      
    </div>
  </div>
    
  <script>
// 写log方法,演示辅助,与主逻辑无关
var log = function (info) {

	document.getElementById('log').innerHTML += (info + '<br>');	
};

var eleFile = document.querySelector('#file');

if (window.FormData) {
	// 压缩图片需要的一些元素和对象
	var reader = new FileReader(), img = new Image();

	// 选择的文件对象
	var file = null;
	
	// 缩放图片需要的canvas
	var canvas = document.createElement('canvas');
	var context = canvas.getContext('2d');
	
	// base64地址图片加载完毕后
	img.onload = function () {
		// 图片原始尺寸
		var originWidth = this.width;
		var originHeight = this.height;
		
	//	log('图片原尺寸是:' + [originWidth, originHeight].join('x'));
		
		// 计算出目标压缩尺寸
		var maxWidth = 400, maxHeight = 400;
		
		// 目标尺寸
		var targetWidth = originWidth, targetHeight = originHeight;
		
		if (originWidth > maxWidth || originHeight > maxHeight) {
			// 图片尺寸超过400x400的限制
			if (originWidth / originHeight > maxWidth / maxHeight) {
				// 更宽,按照宽度限定尺寸
				targetWidth = maxWidth;
				targetHeight = Math.round(maxWidth * (originHeight / originWidth));
			} else {
				targetHeight = maxHeight;
				targetWidth = Math.round(maxHeight * (originWidth / originHeight));
			}
			
		//	log('超过400x400的限制,图片大小限制为' + [targetWidth, targetHeight].join('x'));
		} else {
		//	log('图片尺寸较小,不压缩');
		}
		
		canvas.width = targetWidth;
		canvas.height = targetHeight;
		
		// 清除画布
		context.clearRect(0, 0, targetWidth, targetHeight);
		
		// 图片压缩
		context.drawImage(img, 0, 0, targetWidth, targetHeight);
		
		log('上传进度<span id="percent"></span>');
		// 转为blob并上传
		canvas.toBlob(function (blob) {
			// 图片ajax上传
			var xhr = new XMLHttpRequest();
			// 显示进度的元素
			var elePercent = document.getElementById('percent');
			// 上传文件名
			var filename = encodeURIComponent(file.name).replace(/%/g, '');
			
			// 上传中
			xhr.upload.addEventListener("progress", function(e) {
				elePercent.innerHTML = Math.round(100 * e.loaded / e.total) / 100 + '%';
			}, false);

			// 文件上传成功或是失败
			xhr.onreadystatechange = function(e) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						// 100%进度
						elePercent.innerHTML = '100%';
						
						// 显示上传成功后的图片地址
						var response = xhr.responseText;
						//	log(response);
                           var obj = JSON.parse(response);
                          var image = document.getElementById('myimage');
                                                    var jia_pic = document.getElementById('jia_pic');
jia_pic.style.display="none";
                      image.style.display="block"
image.src = obj.url;
						
					}
				}
			};

			// 开始上传
          var form = new FormData();
				form.append("filename", filename);
          	form.append("myfile", blob);
			xhr.open("POST", 'http://pay.yujianweb.cn/uploadimg.php', true);
			xhr.setRequestHeader("X_FILENAME", filename);
			xhr.send(form);	
		}, file.type || 'image/png');
	};
	
	// 文件base64化,以便获知图片原始尺寸
	reader.onload = function(e) {
		// 图片尺寸
		img.src = e.target.result;
	};
	eleFile.addEventListener('change', function (event) {
		file = event.target.files[0];
		
		if (file.type.indexOf("image") == 0) {
			log('已选择图片'+ file.name +',大小为'+ Math.round(1000 * file.size / (1024*1024)) / 1000 +'M。');

			reader.readAsDataURL(file);	
		} else {
			log('选择的文件非图片,到此为止。');
		}
	});
}
</script>
    
</body>
</html>

php服务器后端页面      uploadimg.php

<?php
define('ROOT',dirname(__FILE__).'/');
    $picname = $_POST['filename']; 
    if ($picname != "") { 
        $type ='.'.substr(strrchr($picname, '.'), 1); //限制上传格式 
 
        if ( $type != ".jpg" && $type != ".png") {
            echo '{"status":2,"content":"图片格式不对!"}';
            exit; 
        }
        $rand = rand(100, 999); 
        $pics = uniqid() . $type; //命名图片名称 
        //上传路径 
        $pic_path = ROOT.'upload/'. $pics; 
     if(move_uploaded_file($_FILES["myfile"]['tmp_name'] , $pic_path)) {
    echo '{"status":1,"name":"'.$picname.'","url":"http://pay.yujianweb.cn/upload/'.$pics.'","content":"上传成功"}';  
} else {
    echo '{"status":0,"name":"'.$picname.'","content":"上传失败"}';  
}
    } 
echo $mes;
      
?>

  
I want to comment

Search

classification

Leave a message
http://blog.yujianweb.cn/index.php/
User login
You have not written any reviews yet!
You have commented!
Can only praise once!
You have a collection!