欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cropperjs实现图片裁剪上传

程序员文章站 2022-04-09 13:09:40
...
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/cropper.css">
  <link rel="stylesheet" href="css/main.css">
	<style type="text/css">
		.inpuFile{
		    display: none;
		}
		.doImg{
			height: 100px;
			width: 100px;
			border: darkgray solid 1px;
			margin-left: 10px;
			text-align: center;
			line-height: 100px;
			 font-size: 50px;
			 font-weight: 900;
			 color: darkgray;
		}
		.doImg:hover{
			 font-size: 80px;
		}
		.imgDiv{
			width: 300px;
			height: 300px;
			margin-left: 300px;
		}
	</style>
</head>
<body>
	
	  <script src="js/jquery.js"></script>
	<script src="js/cropper.js"></script>
	<script src="js/main.js"></script>
	  <!-- 1.一个用于获取上传文件的input,type="file",并且监听onchange事件  -->
	  <br>
	  <br>
	  <div id="doImage" class="doImg" >
		   <img id="cropImg" height="100px" width="100px" style="display: none;">
		  <span>+</span></div>
	<br><br>  
	<input id="imgFile" type="file" hidden="hidden" accept="image/jpg,image/jpeg,image/png,image/PNG" />
	    <!-- 2.一个用于给Cropper.js覆盖使用的img  -->
		<img src="" hidden="hidden" id="cropImg2" style="margin-left: 500px;" alt="" height="300px" width="300px">

		<div class="imgDiv">
		<img id="imm" height="10px" width="100px" src="img/picture.jpg" >
		<br>
		<input type="button" onclick="cutImg()" value="确定" />
		
		<img src="" id="imgg"  height="100px" width="100px">
		</div>
		<script>
			
			$('#imm').cropper({
			    aspectRatio: 4/ 4,
				background:false,
				resizable:false,
				zoomable:true,
				minContainerWidth:100,
				
			    crop: function(data) {
					console.log(data);
			        // Output the result data for cropping image.
			    }
			});
			 function uploadImg(){
			            document.querySelector('#imgReader').click()
			    }
				$("#doImage").click(function(){
					$("#imgFile").click();
				});
				$("#imgFile").change(function(){
					$("#cropImg").parent().find("span").remove();
					 var reads = new FileReader();
					 f = document.getElementById('imgFile').files[0];
					 reads.readAsDataURL(f);
					 reads.onload = function(e) {
					 document.getElementById('cropImg').src = this.result;
					 // document.getElementById('cropImg2').src = this.result;
					 
					 $("#cropImg").css("display", "block");
					 };
					 
				})
				
				function cutImg(){
					var cavVas = $('#imm').cropper("getCroppedCanvas", {});
					 $("#imgg").attr('src',cavVas.toDataURL());
					  eImgBase64 = canVas.toDataURL().substring(22);
				}
				
		</script>
	


  <!-- Scripts -->

  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>

</body>
</html>