libwebp-compress/test/worker.js
2025-07-08 16:27:07 +08:00

77 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 导入wasm模块
let wasmModule;
var Module = {
onRuntimeInitialized: function (e) {
// let baseData= document.getElementById("base64Image").src;
// baseData=baseData.split(",")[1];
// let buffer = base64ToArrayBuffer(baseData);
// decodeToWebpp(buffer);
// document.getElementById("base64Image").src = fileurl;
// decodeIt();
postMessage({ type: 'ready' });
console.log(Module._malloc(4))
},
onAbort: (e) => {
alert(e);
}
};
// 初始化wasm模块
self.importScripts('convert_image_to_webp.js');
// CreateModule().then(module => {
// wasmModule = module;
// postMessage({ type: 'ready' });
// }).catch(err => {
// postMessage({ type: 'error', error: 'Failed to load WASM module: ' + err.message });
// });
// 处理主线程发来的消息
self.onmessage = async function (e) {
const {
buffer,
width,
height,
quality,
} = e.data;
// 显示原始图片大小
let size = (buffer.byteLength / 1024).toFixed(2);
// 转换图像为 Uint8Array
var inputData = new Uint8Array(buffer);
// 分配内存以存储输出 WebP 大小
var outputSizePtr = Module._malloc(4); // 存储输出大小的指针
// 设置目标宽高和质量因子
var inputDataPtr = Module._malloc(inputData.length);
Module.HEAPU8.set(inputData, inputDataPtr);
var webpPtr = Module._convert_image_to_webp(inputDataPtr, inputData.length, width, height,0,0, quality, outputSizePtr);
// 调用 WebAssembly 函数进行图像转换,返回 WebP 数据指针
// 获取 WebP 数据大小
var outputSize = Module.getValue(outputSizePtr, 'i32');
// 从 WebAssembly 内存中读取 WebP 数据
var webpData = new Uint8Array(Module.HEAPU8.buffer, webpPtr, outputSize);
// document.getElementById('result').innerText += ' ' + (Date.now() - startTime) + 'ms';
// 显示 WebP 图片大小
// document.getElementById("webpSize").textContent = `${size}KB => ${(outputSize / 1024).toFixed(2)}KB`;
// 将 WebP 数据转换为 base64并显示
// let img = document.getElementById("webpImage");
// img.src = "data:image/webp;base64," + arrayBufferToBase64(webpData);
// 使用完成后释放内存
Module._free(outputSizePtr);
Module._free(webpPtr);
Module._free(inputDataPtr);
postMessage({ type: 'webp', webpData });
};