37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
/** 图片工具通用任务包装:loading + 错误提示 */
|
||
|
||
export function formatSize(bytes: number): string {
|
||
if (bytes >= 1024 * 1024)
|
||
return `${(bytes / 1024 / 1024).toFixed(2)} MB`
|
||
if (bytes >= 1024)
|
||
return `${(bytes / 1024).toFixed(1)} KB`
|
||
return `${bytes} B`
|
||
}
|
||
|
||
/** 执行一个图片处理任务:自动 loading / 错误 toast,返回 null 表示失败(页面保持原状态) */
|
||
export async function runTask<T>(title: string, fn: () => Promise<T>): Promise<T | null> {
|
||
uni.showLoading({ title, mask: true })
|
||
try {
|
||
const out = await fn()
|
||
return out
|
||
}
|
||
catch (e) {
|
||
// 额度用尽:core.ts 已经弹了「次数用完」的引导层,这里不要再用 toast 叠一层
|
||
if ((e as Error)?.name === 'QuotaExhaustedError')
|
||
return null
|
||
const msg = (e as Error)?.message || '处理失败'
|
||
uni.showToast({ title: msg, icon: 'none' })
|
||
return null
|
||
}
|
||
finally {
|
||
uni.hideLoading()
|
||
}
|
||
}
|
||
|
||
/** 结果文件名:原名-功能.ext */
|
||
export function resultName(src: string, tag: string, ext: string): string {
|
||
const base = src.split('/').pop() || 'image'
|
||
const noExt = base.replace(/\.[^.]+$/, '')
|
||
return `${noExt}-${tag}.${ext}`
|
||
}
|