使用cropper.js怎么裁剪頭像

使用cropper.js怎么裁剪頭像?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

東湖ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ include file="../common_front.jsp" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="${path }/front/plugins/cropper/cropper.css" rel="external nofollow" >
<script src="${path }/front/plugins/cropper/cropper.js"></script>
 <style>
 .container {
  max-width: 640px;
  margin: 20px auto;
 }
 img {
  max-width: 100%;
 }
 #result img{
  max-width: 200px;
  max-height: 200px;
 }
 .cropper-view-box,
 .cropper-face {
  border-radius: 50%;
 }
 </style>
 <script type="text/javascript">
 function getSize(size){
  var num=parseInt(size);
  if(num<=300){//先要求圖片的大小小于300之間
  return num;
  }
  return getSize(num/2);
 }
 function getRoundedCanvas(sourceCanvas) {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var width = sourceCanvas.width;
  var height = sourceCanvas.height;
  width=getSize(width);
  height=width;
  canvas.width = width;
  canvas.height = height;
  context.beginPath();
  //這里是控制裁剪區(qū)域的大?。ㄟ@里也決定你所要生成的圖片的大小和形狀 我這邊用的是圓形的頭像 大家有別的需要可以修改)
  context.arc(width/2, height/2, Math.min(width, height)/2, 0, 2 * Math.PI);
  context.strokeStyle = 'rgba(0,0,0,0)';
  context.stroke();
  context.clip();
  context.drawImage(sourceCanvas, 0, 0, width, height);
  return canvas;
 }
 $(function(){
  var $image = $('#image');
  var $button = $('#button');
  var $result = $('#result');
  var croppable = false;
  $image.cropper({
   aspectRatio: 1,
   viewMode: 1,
   ready: function () {
    croppable = true;
   }
  });
  $button.on('click', function () {
   var croppedCanvas;
   var roundedCanvas;
   if (!croppable) {
    return;
   }
   // 裁剪
  croppedCanvas = $image.cropper('getCroppedCanvas');
  //判斷圖片大小,如果超過1080 則返回
   if(croppedCanvas.width>1080){
   alert("圖片過大,請重新選擇!");
   return false;
   }
   // 生成圓形
  roundedCanvas = getRoundedCanvas(croppedCanvas);
   //將裁剪區(qū)域的圖片轉出圖片的base64編碼,放到表單里提交到后臺。后臺再對其進行解碼,保存。
   $("#icon").val(roundedCanvas.toDataURL());
   $.ajax({
   url:'${path }/front/saveUserIcon',
   data:$("#submitForm").serialize(),
   type:'POST',
   success:function(data){
   if(data.code==200){
    parent.location.reload(); // 父頁面刷新
      var index = parent.layer.getFrameIndex(window.name); //獲取窗口索引
      parent.layer.close(index);
   }else{
   warningAlert(data.msg);
   }
   }
   });
   return false;
 });
 //當選擇完圖片后,直接提交表單到后臺,圖片保存后再回到此頁面。這樣此頁面的圖片裁剪畫布就改變成你所選擇的圖片了
  $("#file").change(function(){
   var fileName=$("#file").val();
   fileName=fileName.toLowerCase(); 
   if((fileName.indexOf(".jpg")!=-1)||(fileName.indexOf(".png")!=-1)||(fileName.indexOf(".jpeg")!=-1)||(fileName.indexOf(".bmp")!=-1)||(fileName.indexOf(".gif")!=-1)){
   $("#imageUploadForm").submit();   
   }else{
   alert("所選圖片格式錯誤或者不支持此類圖片格式!");
   }   
   return false;
  });
 });
</script> 
</head>
<body>
 <div class="container">
 <form enctype="multipart/form-data" method="post" id="imageUploadForm" action="${path}/front/imageUpload" >
 <span class="btn-upload">
  <a href="javascript:void();" rel="external nofollow" class="btn btn-primary radius"><i class="iconfont">&#xf0020;</i> 選擇圖片</a>
  <input type="file" name="file" id="file" class="input-file">
  <input type="hidden" name="originalImage" value="${imageRelativePath}"/>  
 </span>
 </form>
 <div>
 <c:if test="${!empty imageRelativePath }">
  <img id="image" src="${path }/${imageRelativePath}" alt="Picture">
 </c:if>
 <c:if test="${!empty userico }">
  <img id="image" src="${path }/${userico}" alt="Picture">
 </c:if>
 <c:if test="${!empty teachericon }">
  <img id="image" src="${path }/${teachericon}" alt="Picture">
 </c:if>
 </div> 
 <form id="submitForm" action="" method="post">  
  <input type="hidden" name="originalImage" value="${imageRelativePath}"/>
  <input type="hidden" name="icon" id="icon"/>
 </form>
 <input class="btn btn-primary size-M radius" type="button" id="button" value="上傳頭像">
 <div id="result"></div>
 </div>
</body>
</html>

snippet_file_0.txt

下面是我后臺處理方法,大家可以借鑒一下。后臺是ssm框架,主要是保存圖片和圖片轉碼

//用戶上傳頭像
 /**
 * 
 * @param image 選擇的圖片
 * @param model
 * @param userId 用戶id
 * @param userType 用戶類型
 * @param request
 * @param originalImage 上一張臨時圖片
 * @return
 */
 @RequestMapping(value="/imageUpload",method=RequestMethod.POST)
 public String iconImageUpload(@RequestParam(value="file",required=false)MultipartFile image,Model model,@CookieValue("userId")String userId,HttpServletRequest request,String originalImage){
 String basePath="image/";
 //web.xml里面配置的用戶圖片存儲路徑
 String userImagePath=request.getSession().getServletContext().getInitParameter("userImageSavePath");
 //圖片相對路徑 
 String imageRelativePath=FileUtils.fileUpload(image, request,basePath+userImagePath);
 System.out.println("圖片保存路徑------"+imageRelativePath);
 System.out.println("上一張臨時圖片------"+originalImage);
 //刪除上一張臨時圖片
 if(originalImage!=null){
 String basePathTemp=request.getSession().getServletContext().getRealPath("/");
 FileUtils.deleteFile(basePathTemp+originalImage);
 }
 model.addAttribute("imageRelativePath", imageRelativePath);
 model.addAttribute("userId", userId);
 return "/crop_image"; 
 }
 //將裁剪好的頭像由base64還原成圖片
 @ResponseBody
 @RequestMapping(value="/saveUserIcon",method=RequestMethod.POST)
 public Msg saveUserIcon(String icon,@CookieValue("userType")String userType,@CookieValue("userId")String userId,String originalImage,HttpServletRequest request){
 System.out.println("icon-----"+icon);
 //先生成圖片地址
 String realpath=request.getSession().getServletContext().getRealPath("/");
 String basePath="image/";
 String userImagePath=request.getSession().getServletContext().getInitParameter("userImageSavePath");
 Calendar now=Calendar.getInstance();
 String relativePath=basePath+userImagePath+"/"+now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.DAY_OF_MONTH)+"/"+FileUtils.getUUID()+".png";
 String imagePath=realpath+relativePath;
 //將base64 轉換成圖片
 FileUtils.base64ToImage(icon, imagePath);
 //刪除原圖
 if(originalImage!=null){
 FileUtils.deleteFile(realpath+originalImage); 
 }
 return Msg.success();
 }
 //下面是解碼的方法
 public static boolean base64ToImage(String base64, String path) {// 對字節(jié)數(shù)組字符串進行Base64解碼并生成圖片 
  if (base64 == null){ // 圖像數(shù)據(jù)為空 
   return false; 
  } 
  System.out.println(base64);
  // base64 的格式為 “data:image/png;base64,****”,逗號之前都是一些說明性的文字,我們只需要逗號之后的就行了
  base64=base64.split(",")[1];
  BASE64Decoder decoder = new BASE64Decoder(); 
  try { 
   // Base64解碼 
   byte[] bytes = decoder.decodeBuffer(base64); 
   for (int i = 0; i < bytes.length; ++i) { 
    if (bytes[i] < 0) {// 調整異常數(shù)據(jù) 
     bytes[i] += 256; 
    } 
   } 
   // 生成圖片 
   OutputStream out = new FileOutputStream(path); 
   out.write(bytes); 
   out.flush(); 
   out.close(); 
   return true; 
  } catch (Exception e) { 
   return false; 
  } 
 }

關于使用cropper.js怎么裁剪頭像問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。

本文標題:使用cropper.js怎么裁剪頭像
URL標題:http://bm7419.com/article8/jciiip.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供ChatGPT、手機網(wǎng)站建設、App設計服務器托管、域名注冊、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設網(wǎng)站維護公司