使用cropper.js裁剪頭像的實(shí)例代碼
最近項(xiàng)目需要頭像裁剪的功能,在網(wǎng)上找了一下,發(fā)現(xiàn)了github上的cropper項(xiàng)目還不錯(cuò),借鑒了一下。。用起來(lái)挺簡(jiǎn)單的,下面是我做的一個(gè)小例子:
開(kāi)始先放個(gè)成品圖:

下面給出前后端的代碼
前端頁(yè)面是一個(gè)單獨(dú)的jsp頁(yè)面,用來(lái)做彈出層來(lái)裁剪圖片比較好。
關(guān)于jsp頁(yè)面引用的兩個(gè)關(guān)于cropper的 文件,我就不提供了。大家需要的可以去官方的github上去下載。
地址:https://github.com/fengyuanchen/cropper
<%@ 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');
//判斷圖片大小,如果超過(guò)1080 則返回
if(croppedCanvas.width>1080){
alert("圖片過(guò)大,請(qǐng)重新選擇!");
return false;
}
// 生成圓形
roundedCanvas = getRoundedCanvas(croppedCanvas);
//將裁剪區(qū)域的圖片轉(zhuǎn)出圖片的base64編碼,放到表單里提交到后臺(tái)。后臺(tái)再對(duì)其進(jìn)行解碼,保存。
$("#icon").val(roundedCanvas.toDataURL());
$.ajax({
url:'${path }/front/saveUserIcon',
data:$("#submitForm").serialize(),
type:'POST',
success:function(data){
if(data.code==200){
parent.location.reload(); // 父頁(yè)面刷新
var index = parent.layer.getFrameIndex(window.name); //獲取窗口索引
parent.layer.close(index);
}else{
warningAlert(data.msg);
}
}
});
return false;
});
//當(dāng)選擇完圖片后,直接提交表單到后臺(tái),圖片保存后再回到此頁(yè)面。這樣此頁(yè)面的圖片裁剪畫(huà)布就改變成你所選擇的圖片了
$("#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("所選圖片格式錯(cuò)誤或者不支持此類(lèi)圖片格式!");
}
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">󰀠</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
下面是我后臺(tái)處理方法,大家可以借鑒一下。后臺(tái)是ssm框架,主要是保存圖片和圖片轉(zhuǎn)碼
//用戶上傳頭像
/**
*
* @param image 選擇的圖片
* @param model
* @param userId 用戶id
* @param userType 用戶類(lèi)型
* @param request
* @param originalImage 上一張臨時(shí)圖片
* @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里面配置的用戶圖片存儲(chǔ)路徑
String userImagePath=request.getSession().getServletContext().getInitParameter("userImageSavePath");
//圖片相對(duì)路徑
String imageRelativePath=FileUtils.fileUpload(image, request,basePath+userImagePath);
System.out.println("圖片保存路徑------"+imageRelativePath);
System.out.println("上一張臨時(shí)圖片------"+originalImage);
//刪除上一張臨時(shí)圖片
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 轉(zhuǎn)換成圖片
FileUtils.base64ToImage(icon, imagePath);
//刪除原圖
if(originalImage!=null){
FileUtils.deleteFile(realpath+originalImage);
}
return Msg.success();
}
//下面是解碼的方法
public static boolean base64ToImage(String base64, String path) {// 對(duì)字節(jié)數(shù)組字符串進(jìn)行Base64解碼并生成圖片
if (base64 == null){ // 圖像數(shù)據(jù)為空
return false;
}
System.out.println(base64);
// base64 的格式為 “data:image/png;base64,****”,逗號(hào)之前都是一些說(shuō)明性的文字,我們只需要逗號(hào)之后的就行了
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) {// 調(diào)整異常數(shù)據(jù)
bytes[i] += 256;
}
}
// 生成圖片
OutputStream out = new FileOutputStream(path);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
總結(jié)
以上所述是小編給大家介紹的使用cropper.js裁剪頭像的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
js實(shí)現(xiàn)網(wǎng)頁(yè)音樂(lè)播放器
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)網(wǎng)頁(yè)音樂(lè)播放器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
jfinal與bootstrap的登錄跳轉(zhuǎn)實(shí)戰(zhàn)演習(xí)
這篇文章給大家分享jfinal與bootstrap之間的登錄跳轉(zhuǎn),具體內(nèi)容包含有點(diǎn)擊登錄彈出模態(tài)框、點(diǎn)擊登錄確認(rèn)按鈕后的validate、jfinal的validate、jfinal的session管理、ajax請(qǐng)求與返回信息處理、頁(yè)面間智能跳轉(zhuǎn)。感興趣的朋友跟著小編一起看看吧2015-09-09
ionic+html5+API實(shí)現(xiàn)雙擊返回鍵退出應(yīng)用
這篇文章主要為大家詳細(xì)介紹了ionic+html5+API實(shí)現(xiàn)雙擊返回鍵退出應(yīng)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09
JavaScript獲取當(dāng)前頁(yè)面路徑的三種方法
在Web開(kāi)發(fā)中,我們經(jīng)常需要獲取當(dāng)前頁(yè)面的URL路徑,以便進(jìn)行導(dǎo)航、數(shù)據(jù)加載或其他與頁(yè)面相關(guān)的操作,JavaScript提供了幾種方法來(lái)幫助我們實(shí)現(xiàn)這一功能,在本文中,我們將探討幾種常用的方法,需要的朋友可以參考下2024-05-05
JavaScript算法教程之sku(庫(kù)存量單位)詳解
這篇文章主要給大家介紹了JavaScript算法教程之sku(庫(kù)存量單位)的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來(lái)學(xué)習(xí)學(xué)習(xí)吧。2017-06-06
JS中自定義定時(shí)器讓它在某一時(shí)刻執(zhí)行
寫(xiě)一個(gè)方法,讓它在某一時(shí)刻執(zhí)行,即需要在JS中寫(xiě)一個(gè)定時(shí)器,當(dāng)時(shí)間達(dá)到要求時(shí)間時(shí),需要執(zhí)行的方法自動(dòng)執(zhí)行,下面的示例大家可以參考下2014-09-09
SharePoint 客戶端對(duì)象模型 (一) ECMA Script
今天開(kāi)始SharePoint Client對(duì)象模型的介紹,簡(jiǎn)而言之,SharePoint通過(guò)WCF技術(shù)在服務(wù)端提供數(shù)據(jù)服務(wù),這些服務(wù)提供的內(nèi)容相當(dāng)于SharePoint API的一個(gè)子集2011-05-05
javascript實(shí)現(xiàn)簡(jiǎn)易的計(jì)算器
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)簡(jiǎn)易的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01

