import { num, choice, source, pixels, luminance, canvas, png, json, plain } from './common.js';
const fields = {
'image-histogram': [], 'pixel-inspector': [num('x', 'X 坐标', 0, 0, 15999), num('y', 'Y 坐标', 0, 0, 15999)],
'alpha-inspector': [], 'image-hash': [choice('algorithm', '哈希算法', [['SHA-256', 'SHA-256'], ['SHA-384', 'SHA-384'], ['SHA-512', 'SHA-512']])],
'duplicate-images': [], 'dimension-audit': [], 'contrast-map': [], 'blur-assessment': [], 'image-entropy': [], 'print-size': [num('dpi', '印刷 DPI', 300, 36, 2400)],
};
const hex = (array) => Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('');
const digest = async (buffer, algorithm = 'SHA-256') => hex(new Uint8Array(await crypto.subtle.digest(algorithm, buffer)));
const csv = (value) => `"${String(value).replaceAll('"', '""')}"`;
export function getImplementation(id) {
return { fields: fields[id], async run({ images, files, values: v }) {
if (id === 'image-hash') return [json({ file: files[0].name, bytes: files[0].size, algorithm: v.algorithm, hash: await digest(await files[0].arrayBuffer(), v.algorithm) })];
if (id === 'dimension-audit') return [plain('file,width,height,ratio,megapixels\n' + images.map((im) => [csv(im.file.name), im.width, im.height, (im.width / im.height).toFixed(5), (im.width * im.height / 1e6).toFixed(4)].join(',')).join('\n'), 'dimensions.csv', 'text/csv')];
if (id === 'duplicate-images') {
if (images.length < 2) throw new Error('请至少选择两张图片。'); const records = [];
for (const image of images) { const node = source([image]); records.push({ name: image.file.name, width: image.width, height: image.height, fileHash: await digest(await image.file.arrayBuffer()), pixelHash: await digest(pixels(node).data) }); }
const groups = (key) => Object.values(Object.groupBy(records, (r) => `${key === 'pixelHash' ? `${r.width}x${r.height}:` : ''}${r[key]}`)).filter((g) => g.length > 1).map((g) => g.map((r) => r.name));
return [json({ files: records, identicalFiles: groups('fileHash'), identicalDecodedPixels: groups('pixelHash') })];
}
const out = source(images), w = out.width, h = out.height, data = pixels(out), d = data.data;
if (id === 'pixel-inspector') {
if (v.x >= w || v.y >= h) throw new Error(`坐标超出图片 ${w} × ${h}。`); const i = (v.y * w + v.x) * 4, rgba = Array.from(d.slice(i, i + 4)); return [json({ x: v.x, y: v.y, rgba, hex: `#${hex(rgba)}` })];
}
if (id === 'print-size') return [json({ pixels: { width: w, height: h }, dpi: v.dpi, inches: { width: w / v.dpi, height: h / v.dpi }, millimeters: { width: w / v.dpi * 25.4, height: h / v.dpi * 25.4 }, note: '按指定 DPI 估算,不修改文件内分辨率元数据。' })];
const histogram = Array.from({ length: 4 }, () => Array(256).fill(0)); let transparent = 0, opaque = 0;
const gray = new Float32Array(w * h);
for (let i = 0; i < d.length; i += 4) { const l = luminance(d[i], d[i + 1], d[i + 2]); gray[i / 4] = l; for (let k = 0; k < 3; k++) histogram[k][d[i + k]]++; histogram[3][Math.round(l)]++; if (d[i + 3] === 0) transparent++; if (d[i + 3] === 255) opaque++; }
if (id === 'alpha-inspector') { for (let i = 0; i < d.length; i += 4) { d[i] = d[i + 1] = d[i + 2] = d[i + 3]; d[i + 3] = 255; } out.getContext('2d').putImageData(data, 0, 0); return [await png(out, 'alpha.png'), json({ pixels: w * h, transparent, opaque, partial: w * h - transparent - opaque })]; }
if (id === 'image-histogram') {
const chart = canvas(768, 320, '#ffffff'), ctx = chart.getContext('2d'), max = Math.max(...histogram.flat()); ctx.lineWidth = 1.5;
histogram.forEach((bins, k) => { ctx.strokeStyle = ['#d14343', '#22804e', '#2868bf', '#333333'][k]; ctx.beginPath(); bins.forEach((count, x) => { const y = 300 - count / max * 280; if (x) ctx.lineTo(3 * x, y); else ctx.moveTo(0, y); }); ctx.stroke(); }); return [await png(chart, 'histogram.png'), json({ red: histogram[0], green: histogram[1], blue: histogram[2], luminance: histogram[3], note: '统计所有解码像素,含透明像素的 RGB。' })];
}
if (id === 'image-entropy') { const entropy = histogram[3].reduce((sum, count) => { const p = count / (w * h); return count ? sum - p * Math.log2(p) : sum; }, 0); return [json({ bitsPerPixel: entropy, bins: histogram[3], maximum: 8, note: '8 位亮度分布熵,不代表压缩率或画质评分。' })]; }
if (w < 3 || h < 3) throw new Error('图片至少需要 3 × 3 像素。');
const at = (x, y) => gray[y * w + x]; let sum = 0, sum2 = 0, count = 0;
const edges = canvas(w, h, '#000000'), ed = edges.getContext('2d').getImageData(0, 0, w, h);
for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
let value;
if (id === 'blur-assessment') value = at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1) - 4 * at(x, y);
else { const gx = -at(x - 1, y - 1) + at(x + 1, y - 1) - 2 * at(x - 1, y) + 2 * at(x + 1, y) - at(x - 1, y + 1) + at(x + 1, y + 1), gy = -at(x - 1, y - 1) - 2 * at(x, y - 1) - at(x + 1, y - 1) + at(x - 1, y + 1) + 2 * at(x, y + 1) + at(x + 1, y + 1); value = Math.hypot(gx, gy); const i = (y * w + x) * 4; ed.data[i] = ed.data[i + 1] = ed.data[i + 2] = Math.min(255, value); }
sum += value; sum2 += value * value; count++;
}
if (id === 'blur-assessment') return [json({ laplacianVariance: Math.max(0, sum2 / count - (sum / count) ** 2), samples: count, note: '仅适合同尺寸、同内容的相对比较;没有通用合格阈值。' })];
edges.getContext('2d').putImageData(ed, 0, 0); return [await png(edges, 'edges.png'), json({ meanSobelMagnitude: sum / count, samples: count })];
} };
}