export const limits = { fileBytes: 20 * 1024 * 1024, totalBytes: 60 * 1024 * 1024, pixels: 20_000_000, totalPixels: 40_000_000 };
export const escapeHTML = (value) => String(value).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
export const bytes = (n) => n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 / 1024).toFixed(2)} MB`;
export function dimensions(width, height, maxPixels = limits.pixels) {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 16000 || height > 16000 || width * height > maxPixels) {
throw new Error(`尺寸应为 1–16000 的整数,且总像素不超过 ${(maxPixels / 1_000_000).toFixed(0)} MP。`);
}
}
export function canvas(width, height, background) {
dimensions(width, height);
const node = document.createElement('canvas');
node.width = width; node.height = height;
if (background) { const ctx = node.getContext('2d'); ctx.fillStyle = background; ctx.fillRect(0, 0, width, height); }
return node;
}
export function raster(item, width = item.width, height = item.height, background) {
const node = canvas(width, height, background);
node.getContext('2d').drawImage(item.image, 0, 0, width, height);
return node;
}
export async function encode(node, type = 'image/png', quality = 0.9) {
const blob = await new Promise((resolve) => node.toBlob(resolve, type, quality));
if (!blob || blob.type !== type) throw new Error('当前浏览器不支持所选格式,请使用 PNG 或更换浏览器。');
return blob;
}
export function filename(original, suffix, mime) {
const stem = original.replace(/\.[^.]+$/, '').replace(/[\\/:*?"<>|\x00-\x1f]/g, '_').slice(0, 100) || 'image';
return `${stem}-${suffix}.${({ 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'application/json': 'json' })[mime]}`;
}
export function result(blob, name, note = '') { return { blob, name, note }; }
export function jsonResult(data, name) { return result(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }), name); }
export async function loadFiles(files, count, accept) {
if (!files.length) throw new Error('请先选择图片。');
if (files.length > count) throw new Error(`本工具最多选择 ${count} 张图片。`);
if (files.reduce((n, f) => n + f.size, 0) > limits.totalBytes) throw new Error('本次文件总大小不能超过 60 MB。');
const loaded = [];
try {
for (const file of files) {
if (!accept.split(',').includes(file.type)) throw new Error(`不支持的文件格式:${file.name}。`);
if (file.size > limits.fileBytes) throw new Error(`单张图片不能超过 20 MB:${file.name}。`);
const url = URL.createObjectURL(file);
const image = new Image();
try { image.src = url; await image.decode(); dimensions(image.naturalWidth, image.naturalHeight); }
catch { URL.revokeObjectURL(url); throw new Error(`图片损坏、无法解码或超过 20 MP:${file.name}。`); }
loaded.push({ file, url, image, width: image.naturalWidth, height: image.naturalHeight, delay: 300 });
if (loaded.reduce((n, item) => n + item.width * item.height, 0) > limits.totalPixels) throw new Error('本次图片总像素不能超过 40 MP。');
}
return loaded;
} catch (error) { release(loaded); throw error; }
}
export function release(items) { for (const item of items) if (item.url) URL.revokeObjectURL(item.url); }
export function download(blob, name) {
const url = URL.createObjectURL(blob); const a = document.createElement('a');
try {
a.href = url; a.download = name; a.click();
} catch (error) {
URL.revokeObjectURL(url);
throw error;
}
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export function number(form, key) { return Number(form.elements.namedItem(key).value); }
export function value(form, key) { return form.elements.namedItem(key).value; }
export function field(label, content) { return `<label class="field"><span>${label}</span>${content}</label>`; }
export function input(key, val, min, max, step = 1) { return `<input name="${key}" type="number" value="${val}" min="${min}" max="${max}" step="${step}" required>`; }
export function select(key, values) { return `<select name="${key}">${values.map(([v, label]) => `<option value="${v}">${label}</option>`).join('')}</select>`; }
export const quality = () => field('画质', '<div class="range"><input name="quality" type="range" min="0.1" max="1" step="0.05" value="0.8"><output>80%</output></div>');
export const format = (values = [['image/png', 'PNG'], ['image/jpeg', 'JPEG'], ['image/webp', 'WebP']]) => field('输出格式', select('format', values));
export const background = () => field('背景色', '<input type="color" name="background" value="#ffffff">');