裁剪圖以下html
前端html:
<div id="crop-box"></div>
用來盛放將會使用的裁剪區域
基本用法(搭配angular5)
1. 生成一個新的裁剪區域
private newCroppie(data, height) {
if (this.croppie) {
this.destroyCroppie();
}
this.croppie = new Croppie(document.querySelector('#crop-box'), this.resizeCroppie(height));
this.croppie.bind({
url: data
});
}
2. 裁剪區域的基本配置
private resizeCroppie(height) {
return this.resizeObj = {
viewport: { width: 1200, height: this.value },
boundary: { width: 1250, height: Number(this.value) + 50 },
showZoomer: true,
enableOrientation: true
}
}
3. 獲取裁剪的數據
private getResult() {
this.croppie.result({ type: 'rawcanvas' }).then((result) => {
return this.compressImg(result, 1024)
});
}
4. 銷燬裁剪區域
private destroyCroppie() {
this.cropBarDisplay = false;
this.croppie.destroy();
this.croppie = null; //這個手動將整個裁剪區域爲空,由於在ngOnChange週期使用的緣由
}
複製代碼
- 這個類型不支持image/jpg,若是你將.jpg的進行轉換成base64,他會直接將image的類型轉換成image/jpeg.
- 若是你使用的的圖片類型不屬於MIME的範圍,那麼會直接轉換成image/png
- 這個0到1的範圍,並非精確的比例,還要綜合考慮圖片的質量等因素
- 對於圖片類型是image/png的圖片是沒辦法進行圖片壓縮的,image/jpeg,image/webp是能夠進行圖片壓縮的
private compressImg(canvasResult, size) {
let imgBase64 = canvasResult.toDataURL('image/jpeg', 1);
let base64Kilobyte = (imgBase64.length - 814) / 1.37 / 1024; //將base64的結果轉換成kb
let currentQuality = 1
//經過循環 進行圖片質量的壓縮,直到小於規定的大小才中止
if (base64Kilobyte > size) {
for (let i = 10; i > 0; i--) {
currentQuality -= 0.1;
const quality = parseFloat((currentQuality).toFixed(2));
imgBase64 = canvasResult.toDataURL('image/jpeg', quality);
base64Kilobyte = (imgBase64.length - 814) / 1.37 / 1024;
if (base64Kilobyte < size) {
break;
}
}
}
return imgBase64;
}
複製代碼