export const ARTICLE_IMAGE_LIMIT = 2 * 1024 * 1024; export const ARTICLE_IMAGE_TYPES = [ 'image/jpeg', 'image/png', 'image/webp', 'image/gif', ]; export function articleImageSource(value) { const source = String(value || '').trim(); if (source.startsWith('data:')) { const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]+={0,2})$/i.exec( source, ); if (!match || match[2].length % 4) return ''; const bytes = (match[2].length * 3) / 4 - (match[2].match(/=+$/)?.[0].length || 0); return bytes > 0 && bytes <= ARTICLE_IMAGE_LIMIT ? source : ''; } try { const url = new URL(source); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? url.href : ''; } catch { return ''; } } export async function readArticleImage(file) { if (!ARTICLE_IMAGE_TYPES.includes(file.type)) throw new Error('正文图片仅支持 JPG、PNG、WebP、GIF 格式'); if (!file.size || file.size > ARTICLE_IMAGE_LIMIT) throw new Error('单张正文图片大小不能超过 2 MB,且不能为空'); try { const bitmap = await createImageBitmap(file); bitmap.close(); } catch { throw new Error('无法读取图片,请选择有效的图片文件'); } return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error('图片读取失败,请重新选择或粘贴')); reader.readAsDataURL(file); }); }