Files
image-workbench-desktop/src/image-display-thumb.js
T
2026-11-21 06:53:32 +08:00

150 lines
5.7 KiB
JavaScript

/* image-display-thumb.js —— 画布内大图的显示缩略图生成队列(v3.25.67 起,v3.25.73 重写)
*
* 职责:把一张原图(blob:/http/dataURL)变成 ≤768 的显示缩略图,并交给宿主缓存/落盘。
*
* v3.25.73(参考 basketikun/infinite-canvas 的 image-thumbnail.ts):
* ① 优先 createImageBitmap(blob) → canvas → toBlob('image/webp', 0.86) → **objectURL**
* —— 解码在目标尺寸完成,产物是 Blob(objectURL)而不是 dataURL,不常驻 JS 堆;
* ② 拿不到字节(跨域等)才回落到 <img> + canvas + dataURL(老路径);
* ③ 并发上限 2 + requestIdleCallback 空闲启动,避免打开画布时同时解码几十张;
* ④ 宿主注入 save(key, blobOrDataUrl):负责落盘(文件存储)。
*/
;(function (global) {
'use strict'
function create (opts) {
const o = opts || {}
const max = Math.max(64, Number(o.max) || 768)
const cacheMax = Math.max(16, Number(o.cacheMax) || 300)
const concurrency = Math.max(1, Number(o.concurrency) || 2)
const cache = o.cache
const pending = o.pending
if (!cache || !pending) throw new Error('cache/pending required')
const queue = []
let running = 0
let scheduled = false
const remember = (key, val) => {
if (cache.size >= cacheMax) {
const first = cache.keys().next().value
if (first !== undefined) cache.delete(first)
}
cache.set(key, val)
}
const bump = () => { try { if (typeof o.bump === 'function') o.bump() } catch (e) { /* ignore */ } }
const save = (key, payload) => { try { if (typeof o.save === 'function') o.save(key, payload) } catch (e) { /* ignore */ } }
// ① 优先路径:字节 → bitmap → 缩放 → WebP Blob → objectURL
const runBitmap = async (key, v) => {
if (typeof fetch !== 'function' || typeof createImageBitmap !== 'function') return false
const resp = await fetch(v)
if (!resp || !resp.ok) return false
const blob = await resp.blob()
const bitmap = await createImageBitmap(blob)
const iw = bitmap.width || 0
const ih = bitmap.height || 0
try {
if (!iw || !ih) return false
if (iw <= max && ih <= max) {
remember(key, v)
return true
}
const scale = Math.min(max / Math.max(1, iw), max / Math.max(1, ih))
const cw = Math.max(1, Math.round(iw * scale))
const ch = Math.max(1, Math.round(ih * scale))
const cv = document.createElement('canvas')
cv.width = cw
cv.height = ch
const ctx = cv.getContext('2d')
if (!ctx) return false
ctx.drawImage(bitmap, 0, 0, cw, ch)
const small = await new Promise((res) => {
try { cv.toBlob((b) => res(b || null), 'image/webp', 0.86) } catch (e) { res(null) }
})
if (!small) return false
const url = URL.createObjectURL(small)
remember(key, url)
save(key, small)
return true
} finally {
try { bitmap.close() } catch (e) { /* ignore */ }
}
}
// ② 回落路径:<img> + canvas → dataURL(跨域时 fetch 会失败)
const runImg = (key, v) => new Promise((resolve) => {
if (typeof document === 'undefined' || typeof Image !== 'function') { resolve(false); return }
const img = new Image()
try { img.decoding = 'async' } catch (e) { /* ignore */ }
img.onload = () => {
try {
const iw = img.naturalWidth || 0
const ih = img.naturalHeight || 0
if (iw <= max && ih <= max) { remember(key, v); resolve(true); return }
const scale = Math.min(max / Math.max(1, iw), max / Math.max(1, ih))
const cw = Math.max(1, Math.round(iw * scale))
const ch = Math.max(1, Math.round(ih * scale))
const cv = document.createElement('canvas')
cv.width = cw
cv.height = ch
const ctx = cv.getContext('2d')
if (!ctx) { resolve(false); return }
ctx.drawImage(img, 0, 0, cw, ch)
const small = cv.toDataURL('image/jpeg', 0.78)
remember(key, small)
save(key, small)
resolve(true)
} catch (e) { remember(key, v); resolve(false) }
}
img.onerror = () => {
try { if (!(typeof o.isTransient === 'function' && o.isTransient(v))) remember(key, v) } catch (e) { /* ignore */ }
resolve(false)
}
img.src = v
})
const run = async (key, v) => {
let ok = false
try { ok = await runBitmap(key, v) } catch (e) { ok = false }
if (!ok) { try { ok = await runImg(key, v) } catch (e2) { ok = false } }
if (ok) bump()
return ok
}
const pump = () => {
while (running < concurrency && queue.length) {
const job = queue.shift()
running++
run(job.key, job.v).catch(() => { /* ignore */ }).then(() => {
running--
try { pending.delete(job.key) } catch (e) { /* ignore */ }
pump()
})
}
}
const schedule = () => {
if (scheduled) return
scheduled = true
const kick = () => { scheduled = false; pump() }
try {
if (typeof requestIdleCallback === 'function') requestIdleCallback(kick, { timeout: 1200 })
else setTimeout(kick, 60)
} catch (e) { setTimeout(kick, 60) }
}
return {
queue: function (key, v) {
if (!key || cache.has(key) || pending.has(key)) return false
pending.add(key)
queue.push({ key: key, v: v })
schedule()
return true
},
stats: function () { return { queued: queue.length, running: running } }
}
}
global.IWBImageDisplayThumb = { create: create }
})(typeof window !== 'undefined' ? window : globalThis)