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

214 lines
8.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.
/* 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 }
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
}
S.exportOptions = {
preset: get('preset', DEFAULT_EXPORT.preset) === 'ecom800' ? 'ecom800' : 'original',
format: ['png', 'jpeg', 'webp'].indexOf(get('format', DEFAULT_EXPORT.format)) >= 0 ? get('format', DEFAULT_EXPORT.format) : 'png',
bg: get('bg', DEFAULT_EXPORT.bg) === 'white' ? 'white' : 'transparent',
maxKB: Math.max(0, Number(get('maxKB', 0)) || 0),
size: Math.max(64, Number(get('size', 800)) || 800)
}
if (S.exportOptions.preset === 'ecom800' && !S.exportOptions.maxKB) S.exportOptions.maxKB = 500
renderExportUI()
}
export function setExportOption(key, value) {
if (!S.exportOptions) loadExportOptions()
S.exportOptions[key] = value
if (key === 'preset' && value === 'ecom800') S.exportOptions.maxKB = 500
if (key === 'preset' && value === 'original') S.exportOptions.maxKB = 0
const st = settings()
if (st && typeof st.set === 'function') {
try { st.set(SETTINGS_KEY[key], value) } catch (e) { /* ignore */ }
}
renderExportUI()
}
/** 顶栏输出设置面板:按钮态 + 预设摘要 */
export function renderExportUI() {
const o = S.exportOptions || DEFAULT_EXPORT
const root = runtime.el
if (!root) return
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))
})
const summary = root.querySelector('.iwb-editor-export-summary')
if (summary) summary.textContent = o.preset === 'ecom800'
? (o.size + '×' + o.size + ' · ' + o.format.toUpperCase() + (o.maxKB ? ' · ≤' + o.maxKB + 'KB' : ''))
: ('原尺寸 ' + S.imgW + '×' + S.imgH + ' · ' + o.format.toUpperCase())
}
/** 事件委托:输出设置面板(下拉容器常驻 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 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 (o.bg === 'white' || o.format === 'jpeg') { 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 (o.bg === 'white' || o.format === 'jpeg') {
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'
const limit = 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 info = { bytes: blob.size, width: canvas.width, height: canvas.height, format: S.exportOptions.format, preset: S.exportOptions.preset }
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')
}