因?yàn)轫?xiàng)目需要壓縮字符串和二進(jìn)制感帅,找到了pako這個(gè)庫(kù):
https://github.com/nodeca/pako
https://gitee.com/renew_old_romance/pako/tree/master
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pako/index.d.ts
一绷柒、簡(jiǎn)單介紹
參考Javascript 簡(jiǎn)單實(shí)現(xiàn)Gzip 壓縮字符串 基于pako.js
<script>
function input() {
const input = document.getElementById('input').value;
const ys = zip(input);
const jy = unzip(ys);
document.getElementById('yw').innerText = input;
document.getElementById('ys').innerText = ys;
document.getElementById('jy').innerText = jy;
document.getElementById('ysl').innerText =
(Math.round(length(ys) / length(input) * 10000) / 100.00 + "%");
}
// 解壓
function unzip(b64Data) {
let strData = atob(b64Data);
const charData = strData.split('').map(function (x) {
return x.charCodeAt(0);
});
const binData = new Uint8Array(charData);
const data = pako.inflate(binData);
strData = String.fromCharCode.apply(null, new Uint16Array(data));
return decodeURIComponent(strData);
}
// 壓縮
function zip(str) {
const binaryString = pako.gzip(encodeURIComponent(str), {to: 'string'})
return btoa(binaryString);
}
// 占用字節(jié)數(shù)計(jì)算(UTF-8)
function length(str) {
let total = 0, charCode, i, len;
for (i = 0, len = str.length; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode <= 0x007f) {
total += 1;
} else if (charCode <= 0x07ff) {
total += 2;
} else if (charCode <= 0xffff) {
total += 3;
} else {
total += 4;
}
}
return total;
}
</script>
二、二進(jìn)制壓縮/解壓縮
//壓縮
public static deflatePlan(b: model_a.Byte): Uint8Array {
return pako.deflate(new Uint8Array(b.buffer));
}
//解壓
public static inflatePlan(b: Uint8Array): Uint8Array {
return pako.inflate(b);
}
1.壓縮后存儲(chǔ)成本地文件
let e = PlanTool.encodePlan(data);
console.log("編碼數(shù)據(jù):", e);
let d = PlanTool.decodePlan(e);
console.log("畫墻方案編碼然后解碼:", d);
//壓縮后存儲(chǔ)
let plan = PlanTool.deflatePlan(e);
PlanTool.saveForWebBrowser(new Blob([plan.buffer]), "plan");
//---------------------------------------------
// let str = JSON.stringify(obj);
// let b = new Blob([str]);
public static saveForWebBrowser(b: Blob, fileName: string) {
let downloadLink = document.createElement('a');
downloadLink.download = fileName;
downloadLink.innerHTML = 'Download File';
if (window.URL != null) {
downloadLink.href = window.URL.createObjectURL(b);
} else {
downloadLink.href = window.URL.createObjectURL(b);
downloadLink.onclick = () => {
document.body.removeChild(downloadLink);
};
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
2.加載本地文件后夺饲,解壓縮
//https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
let oReq = new XMLHttpRequest();
oReq.open("GET", "resources/plan.txt", true);
oReq.responseType = "arraybuffer";
oReq.onload = () => {
let arrayBuffer = oReq.response as ArrayBuffer; // 注意:不是oReq.responseText
if (arrayBuffer) {
//解壓
let byteArray = new Uint8Array(arrayBuffer);
let d = PlanTool.inflatePlan(byteArray);
//解碼
let b = new model_a.Byte(d.buffer);
let decodeData = PlanTool.decodePlan(b);
console.log("畫墻方案編碼然后解碼:", decodeData);
let scene = Eventtower.instance.getAtt(TGetGloba.GET_STAGE_MANAGER).scene;
let idToContent = Eventtower.instance.getAtt(TGetGloba.GET_STAGE_MANAGER).idToContent;
scene.decodeToObject(decodeData, idToContent);
//性能測(cè)試
PlanTool.benchmarkDecodePlan(b);
PlanTool.benchmarkInflatePlan(byteArray);
}
};
oReq.send(null);
三、字符串壓縮/解壓縮
private unzip(b64Data) {
var strData = atob(b64Data);
// Convert binary string to character-number array
var charData = strData.split('').map(function (x) { return x.charCodeAt(0); });
// Turn number array into byte-array
var binData = new Uint8Array(charData);
// unzip
var data = pako.inflate(binData);
// Convert gunzipped byteArray back to ascii string:
return this.ab2str(data);
}
private zip(str) {
var binaryString = pako.gzip(str, { to: 'string' });
let v = this.ab2str(binaryString as any);
return btoa(v);
}
// ArrayBuffer轉(zhuǎn)為字符串施符,參數(shù)為ArrayBuffer對(duì)象
private ab2str(buf: ArrayBuffer): string {
var binaryString = '';
let bytes = new Uint16Array(buf);
let length = bytes.length;
for (var i = 0; i < length; i++) {
binaryString += String.fromCharCode(bytes[i]);
}
return binaryString;
}
因?yàn)樽址枰c后端通訊往声,所以使用了bota/atob進(jìn)行base64編碼。
1.ArrayBuffer轉(zhuǎn)為字符串的問(wèn)題
關(guān)于字符串與二進(jìn)制處理戳吝,可以參考jsmpeg系列一 基礎(chǔ)知識(shí) 字符處理 ArrayBuffer TypedArray浩销,其中提到了ArrayBuffer與字符串的互相轉(zhuǎn)換。
ArrayBuffer轉(zhuǎn)為字符串听哭,或者字符串轉(zhuǎn)為ArrayBuffer慢洋,有一個(gè)前提,即字符串的編碼方法是確定的陆盘。假定字符串采用UTF-16編碼(JavaScript的內(nèi)部編碼方式)普筹,可以自己編寫轉(zhuǎn)換函數(shù)。
// ArrayBuffer轉(zhuǎn)為字符串隘马,參數(shù)為ArrayBuffer對(duì)象
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
// 字符串轉(zhuǎn)為ArrayBuffer對(duì)象太防,參數(shù)為字符串
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 每個(gè)字符占用2個(gè)字節(jié)
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
但是,ab2str這種寫法酸员,在實(shí)際使用中蜒车,如果buf過(guò)大讳嘱,會(huì)有Maximum call stack size exceeded
堆棧溢出。
可以參考javascript - js數(shù)組轉(zhuǎn)字符串 - 在字符串和ArrayBuffers之間轉(zhuǎn)換酿愧,改為for的寫法:
var
binaryString = '',
bytes = new Uint8Array(arrayBuffer),
length = bytes.length;
for (var i = 0; i < length; i++) {
binaryString += String.fromCharCode(bytes[i]);
}