javascript 處理圖檔壓縮、剪切、模糊和上傳
最近在研究H5前端圖檔處理相關技術,方向有圖檔壓縮、裁切、旋轉、模糊等,現在已經整理成對應的demo,上傳至github。
一:js腳本實作圖檔壓縮 - CompressImageUtiles
特點:
1 體積小,4kb;
2 支援blob格式上傳和base64格式上傳
原圖 5.4MB
壓縮後136KB
用法:
// html
<input type="file" id="input-img">
//引入腳本
<script src="./CompressImageUtiles.js"></script>
<script>
/**
* 支援blob格式上傳和base64格式上傳
* */
let inputDom = document.querySelector('#input-img')
inputDom.onchange = function(){
const fileObj = inputDom.files[0];
_compressAndUploadFile(fileObj);
}
function _compressAndUploadFile(file){
compressImage(file).then(resultObj => {
let {canvas,blob,base64,fileName,oSize} = resultObj
if (blob.size > oSize){
that._uploadFile(file, fileName);
} else {
//壓縮後比原來小,上傳壓縮後的
_uploadFile(blob, fileName)
}
// 下載下傳
downloadImgFromBlob(blob,fileName)
})
}
//上傳
function _uploadFile(file){
let params = new FormData();
params.append("file", file);
}
demo位址:https://github.com/zhangfeng001/compressUtls-demo
ssh:[email protected]:zhangfeng001/compressUtls-demo.git
二:jq插件 實作圖檔剪切、旋轉 - imagecropper
特點:1、炫酷的展現效果,可以完美的應用到項目中,如頭像上傳前選擇區域等
2、輸出多種資料格式,直接浏覽器打開HTML檢視效果
效果預覽:
用法介紹:
1、下載下傳demo 在main.js中看到如下方法,
if (data.method === 'getCroppedCanvas') {
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result.canvas);
console.log(result)
}
2、在此方法中可以檢視log,拿到多種圖檔資料類型 有canvas 、base54、blob,選擇一種上傳即可
demo位址:https://github.com/zhangfeng001/cropper-demo
ssh:[email protected]:zhangfeng001/cropper-demo.git
三:CSS3和canvas實作圖檔模糊處理 blurify.js
特點:體積小,實作更友善,
效果展示
用法介紹:超級簡單
<div class="blurify-container">
<img src="./test/miao.jpg" class="img">
<img src="./test/miao.jpg" class="blurify">
<img src="./test/wang.jpg" class="img">
<img src="./test/wang.jpg" class="blurify">
</div>
<script src="dist/blurify.js"></script>
<script>
(function () {
blurify({
images: document.querySelectorAll('.blurify'),
blur: 2, //值為length px
mode: 'auto', // auto css
});
})();
</script>
demo位址:https://github.com/zhangfeng001/blurify-demo
SSH:[email protected]:zhangfeng001/blurify-demo.git