Files
iwb-plugins-desktop/image-annotate/plugin/editor/export.js
T

297 lines
12 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.
/* export.js - 单张输出管道(P4,随 P1 一起带上)
*
* 一次只产出一个结果:覆盖节点 / 新建节点 / 下载。不做队列、不默认双输出。
* 「电商 800×800 · ≤500KB」是可切换预设(用户 2026-11-04 裁定),
* 预设 / 格式 / 背景存宿主 ctx.settings,下次打开沿用。
*
* 与宿主接口不变:glue.js 仍只收 (blob|dataURL, mode)。
*/
'use strict'
import { S, runtime } from './state.js'
import { getCompositeCanvas } from './tools.js'
import { toast } from './commands.js'
export const DEFAULT_EXPORT = Object.freeze({
preset: 'original', // original | ecom800
format: 'png', // png | jpeg | webp
bg: 'transparent', // transparent | white
maxKB: 0, // 0 = 不限
size: 800 // 预设输出边长
})
const SETTINGS_KEY = {
preset: 'exportPreset', format: 'exportFormat', bg: 'exportBg',
maxKB: 'exportMaxKB', size: 'exportSize'
}
function settings() { return S.callbacks && S.callbacks.settings }
/** 实际输出背景:JPG 没有 alpha 通道,选「透明」也必须落白底。
* 整条输出链(画布、摘要、状态)统一读这里,避免「按钮显示透明、文件是白底」。 */
export function effectiveBg(o) {
o = o || S.exportOptions || DEFAULT_EXPORT
return (o.bg === 'white' || o.format === 'jpeg') ? 'white' : 'transparent'
}
/** 当前输出设置的派生签名:判断「上次输出」是否还代表现在这套设置 */
function exportSignature(o) {
o = o || S.exportOptions || DEFAULT_EXPORT
const ecom = o.preset === 'ecom800'
return [o.preset, o.format, ecom ? o.size : 'orig', effectiveBg(o), ecom ? o.maxKB : 0].join(':')
}
export function loadExportOptions() {
const st = settings()
const get = (k, d) => {
let v = d
if (st && typeof st.get === 'function') {
try { const got = st.get(SETTINGS_KEY[k]); if (got !== undefined && got !== null) v = got } catch (e) { /* ignore */ }
}
return v
}
const preset = get('preset', DEFAULT_EXPORT.preset) === 'ecom800' ? 'ecom800' : 'original'
const format = ['png', 'jpeg', 'webp'].indexOf(get('format', DEFAULT_EXPORT.format)) >= 0 ? get('format', DEFAULT_EXPORT.format) : 'png'
// 体积上限 / 边长只属于电商方图预设。原尺寸分支不继承上一次留下的限制,
// 否则宿主里残留的 exportMaxKB 会让「原尺寸」也偷偷降质。
// null 表示从未设置过(走默认 500),0 表示用户显式选了「不限」——两者必须区分。
const rawMax = get('maxKB', null)
const rawSize = get('size', null)
S.exportOptions = {
preset: preset,
format: format,
// JPG 下背景直接收敛到白底,状态本身自洽,不靠 UI 撒谎
bg: format === 'jpeg' ? 'white' : (get('bg', DEFAULT_EXPORT.bg) === 'white' ? 'white' : 'transparent'),
maxKB: preset === 'ecom800' ? (rawMax === null ? 500 : Math.max(0, Number(rawMax) || 0)) : 0,
size: Math.max(64, Number(rawSize === null ? 800 : rawSize) || 800)
}
renderExportUI()
}
export function setExportOption(key, value) {
if (!S.exportOptions) loadExportOptions()
const o = S.exportOptions
const st = settings()
const persist = (k, v) => {
if (st && typeof st.set === 'function') { try { st.set(SETTINGS_KEY[k], v) } catch (e) { /* ignore */ } }
}
if (key === 'preset') {
o.preset = value === 'ecom800' ? 'ecom800' : 'original'
o.maxKB = o.preset === 'ecom800' ? 500 : 0
persist('preset', o.preset)
// maxKB 必须一起写回:只改内存的话,下次打开会被旧的 exportMaxKB 让限制「复活」
persist('maxKB', o.maxKB)
} else if (key === 'format') {
o.format = ['png', 'jpeg', 'webp'].indexOf(value) >= 0 ? value : 'png'
persist('format', o.format)
if (o.format === 'jpeg' && o.bg !== 'white') {
o.bg = 'white'
persist('bg', 'white')
toast('JPG 不支持透明背景,已切换为白底', 'info')
}
} else if (key === 'bg') {
if (o.format === 'jpeg') { renderExportUI(); return } // 按钮已禁用,这里兜底
o.bg = value === 'white' ? 'white' : 'transparent'
persist('bg', o.bg)
} else if (key === 'maxKB') {
o.maxKB = Math.max(0, Number(value) || 0)
persist('maxKB', o.maxKB)
} else if (key === 'size') {
o.size = Math.max(64, Number(value) || 800)
persist('size', o.size)
}
renderExportUI()
}
/** 顶栏输出设置面板:按钮态 + 预设摘要(摘要必须反映「实际会输出什么」) */
export function renderExportUI() {
const o = S.exportOptions || DEFAULT_EXPORT
const root = runtime.el
if (!root) return
const ecom = o.preset === 'ecom800'
const jpg = o.format === 'jpeg'
root.querySelectorAll('[data-export-key]').forEach(btn => {
const on = String(o[btn.dataset.exportKey]) === String(btn.dataset.exportValue)
btn.classList.toggle('active', on)
btn.setAttribute('aria-pressed', String(on))
})
// JPG 无 alpha 通道:透明按钮禁用并给出原因,而不是留着高亮却悄悄输出白底
root.querySelectorAll('[data-export-key="bg"]').forEach(btn => {
const blocked = jpg && btn.dataset.exportValue === 'transparent'
btn.disabled = blocked
if (blocked) btn.title = 'JPG 不支持透明背景,已自动使用白底'
else btn.removeAttribute('title')
})
// 边长 / 体积上限只在电商方图预设下有意义
root.querySelectorAll('[data-export-when="ecom800"]').forEach(row => { row.hidden = !ecom })
const summary = root.querySelector('.iwb-editor-export-summary')
if (summary) {
const size = ecom ? (o.size + '×' + o.size) : ('原尺寸 ' + S.imgW + '×' + S.imgH)
const limit = ecom && o.maxKB ? (' · ≤' + o.maxKB + 'KB') : ''
const bg = effectiveBg(o) === 'white' ? '白底' : '透明'
// jpeg 的 MIME 名是 JPEG,但对用户就说 JPG
const fmt = o.format === 'jpeg' ? 'JPG' : o.format === 'webp' ? 'WebP' : 'PNG'
summary.textContent = size + ' · ' + fmt + ' · ' + bg + limit
}
// 「上次输出」只在当前这套设置确实产过结果时才报,否则会误导
const note = root.querySelector('.iwb-editor-export-note')
if (note) {
const le = S.lastExport
note.textContent = (le && le.signature === exportSignature(o))
? ('上次输出 ' + le.width + '×' + le.height + ' · ' + Math.max(1, Math.round(le.bytes / 1024)) + 'KB')
: '一次只输出一个结果;设置会记住'
}
}
/** 事件委托:输出设置面板(下拉容器常驻 DOM,展开由 CSS class 控制) */
export function bindExportUI() {
const root = runtime.el
if (!root) return
const panel = root.querySelector('.iwb-editor-export-settings')
const toggle = root.querySelector('[data-action="toggleExportSettings"]')
if (panel && panel.dataset.bound === '1') return
if (panel) panel.dataset.bound = '1'
if (toggle && panel) {
toggle.addEventListener('mousedown', (e) => e.stopPropagation())
toggle.addEventListener('click', (e) => {
e.stopPropagation()
const open = panel.classList.toggle('open')
toggle.setAttribute('aria-expanded', String(open))
})
}
if (panel) {
panel.addEventListener('mousedown', (e) => e.stopPropagation())
panel.addEventListener('click', (e) => {
const btn = e.target.closest('[data-export-key]')
if (!btn) return
e.stopPropagation()
let v = btn.dataset.exportValue
if (btn.dataset.exportKey === 'maxKB' || btn.dataset.exportKey === 'size') v = Number(v)
setExportOption(btn.dataset.exportKey, v)
})
}
}
/** 合成 → 尺寸/背景处理。返回结果画布(调用方负责释放) */
export function buildOutputCanvas() {
const o = S.exportOptions || DEFAULT_EXPORT
const white = effectiveBg(o) === 'white'
const src = getCompositeCanvas()
let out = src
if (o.preset === 'ecom800') {
const size = o.size
const c = document.createElement('canvas')
c.width = size
c.height = size
const cx = c.getContext('2d')
if (white) { cx.fillStyle = '#ffffff'; cx.fillRect(0, 0, size, size) }
const long = Math.max(S.imgW, S.imgH) || 1
const k = (size * 0.8) / long // 商品长边占比 80%(640px / 800px)
const w = S.imgW * k, h = S.imgH * k
cx.drawImage(src, (size - w) / 2, (size - h) / 2, w, h)
src.width = 0; src.height = 0
out = c
} else if (white) {
const c = document.createElement('canvas')
c.width = S.imgW
c.height = S.imgH
const cx = c.getContext('2d')
cx.fillStyle = '#ffffff'
cx.fillRect(0, 0, c.width, c.height)
cx.drawImage(src, 0, 0)
src.width = 0; src.height = 0
out = c
}
return out
}
function toBlob(canvas, mime, quality) {
return new Promise((resolve, reject) => {
try {
if (typeof canvas.toBlob !== 'function') { reject(new Error('当前环境不支持 toBlob')); return }
canvas.toBlob((blob) => {
if (blob) resolve(blob)
else {
try { resolve(dataUrlToBlob(canvas.toDataURL(mime, quality))) }
catch (e) { reject(e) }
}
}, mime, quality)
} catch (e) { reject(e) }
})
}
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(',')
const meta = dataUrl.slice(0, comma)
const bin = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new Blob([bytes], { type: (/^data:([^;,]+)/.exec(meta) || [])[1] || 'image/png' })
}
/** 编码并按 ≤maxKB 迭代降质(jpeg/webp);PNG 无质量参数,明确提示而不是静默失败 */
export async function encodeOutput(canvas) {
const o = S.exportOptions || DEFAULT_EXPORT
const mime = o.format === 'jpeg' ? 'image/jpeg' : o.format === 'webp' ? 'image/webp' : 'image/png'
// ≤KB 只在电商方图预设下约束;「原尺寸 + 残留 maxKB」不应偷偷降质
const limit = (o.preset === 'ecom800' && o.maxKB > 0) ? o.maxKB * 1024 : 0
let blob = await toBlob(canvas, mime, 0.92)
if (limit && blob.size > limit) {
if (o.format === 'png') {
toast('PNG 无法降质:当前 ' + Math.round(blob.size / 1024) + 'KB,可切换 JPG/WebP 或缩小尺寸', 'warn')
} else {
let q = 0.82
for (let i = 0; i < 8 && blob.size > limit && q >= 0.3; i++) {
blob = await toBlob(canvas, mime, q)
q -= 0.09
}
if (blob.size > limit) toast('已尽力压缩,仍为 ' + Math.round(blob.size / 1024) + 'KB(目标 ≤' + o.maxKB + 'KB)', 'warn')
}
}
return blob
}
/** 发布前准备:返回 Blob + 体积信息,不碰宿主、不关闭编辑器 */
export async function prepareOutput() {
const canvas = buildOutputCanvas()
try {
const blob = await encodeOutput(canvas)
const o = S.exportOptions || DEFAULT_EXPORT
const info = {
bytes: blob.size,
width: canvas.width,
height: canvas.height,
format: o.format,
bg: effectiveBg(o),
preset: o.preset,
maxKB: o.preset === 'ecom800' ? o.maxKB : 0,
// 记下产出时用的设置指纹,UI 才能判断「上次输出」是否还代表当前设置
signature: exportSignature(o)
}
S.lastExport = info
return { blob, info }
} finally {
canvas.width = 0
canvas.height = 0
}
}
/** 下载:一次一个文件,用完立即 revoke blob URL */
export function downloadBlob(blob) {
const o = S.exportOptions || DEFAULT_EXPORT
const ext = o.format === 'jpeg' ? 'jpg' : o.format
const raw = (S.callbacks && S.callbacks.imageName) || 'image.png'
const name = String(raw).replace(/\.[^.]+$/, '') + '_edit.' + ext
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = name
document.body.appendChild(a)
a.click()
if (a.parentNode) a.parentNode.removeChild(a)
setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 2000)
toast('已下载 ' + name + '(' + Math.round(blob.size / 1024) + 'KB)', 'success')
}