Croppie.js之圖片裁剪壓縮上傳
h5圖片裁剪, 壓縮, 上傳, 預覽是常見功能, 幸運的是咱們有cropp.js這款利器.
1. style
<link rel="Stylesheet" href="https://cdn.bootcss.com/croppie/2.6.2/croppie.css" />
<style>
.actions button,
.actions a.btn {
background-color: #189094;
color: white;
padding: 10px 15px;
border-radius: 3px;
border: 1px solid rgba(255, 255, 255, 0.5);
font-size: 16px;
cursor: pointer;
text-decoration: none;
text-shadow: none;
}
.actions button:focus {
outline: 0;
}
.actions .file-btn {
position: relative;
}
.actions .file-btn input[type="file"] {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
}
.actions {
padding: 5px 0;
}
.actions button {
margin-right: 5px;
}
.actions .crop{display:none}
</style>
2.html
<div class="actions">
<button class="file-btn">
<span>上傳</span>
<input type="file" id="upload" value="選擇圖片文件" />
</button>
<div class="crop">
<div id="upload-demo"></div>
<button class="upload-result">裁剪</button>
</div>
<div id="result"></div>
</div>
3.JavaScript
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/croppie/2.6.2/croppie.js"></script>
$(function(){
var $uploadCrop;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
});
}
reader.readAsDataURL(input.files[0]);
}
else {
alert("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
},
showZoomer: false,
});
$('#upload').on('change', function () {
$(".crop").show();
readFile(this);
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', 'canvas').then(function (resp) {
popupResult({
src: resp
});
});
});
function popupResult(result) {
var html;
if (result.html) {
html = result.html;
}
if (result.src) {
html = '<img src="' + result.src + '" />';
}
$("#result").html(html);
}
});
croppie.js挺好用的圖片處理插件, 另外還有較好的插件有待研究
http://foliotek.github.io/Cro...
https://github.com/tapmodo/Jcrop
https://fengyuanchen.github.i...