import { isGeneralImageFile, loadOrientedCanvasFromFile } from './imageFileLimits'; /** 与 multer / invoices 桶上限一致 */ export const SUPPLIER_INVOICE_MAX_BYTES = 10 * 1024 * 1024; const COMPRESS_TARGET_BYTES = 8 * 1024 * 1024; const MAX_DIMENSION = 1920; export function isSupplierInvoicePdf(file: File): boolean { const type = String(file.type || '').toLowerCase(); if (type === 'application/pdf') return true; return file.name.toLowerCase().endsWith('.pdf'); } export function isSupplierInvoiceImage(file: File): boolean { const type = String(file.type || '').toLowerCase(); if (type.startsWith('image/')) return true; return isGeneralImageFile(file); } export function isSupplierInvoiceFile(file: File): boolean { return isSupplierInvoicePdf(file) || isSupplierInvoiceImage(file); } function dataUrlToJpegFile(dataUrl: string, originalName: string): File { const comma = dataUrl.indexOf(','); const b64 = comma >= 0 ? dataUrl.slice(comma + 1) : ''; const bin = atob(b64); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); const base = originalName.replace(/\.[^.]+$/, '') || 'invoice'; return new File([bytes], `${base}.jpg`, { type: 'image/jpeg' }); } function scaleCanvas(source: HTMLCanvasElement, width: number, height: number): HTMLCanvasElement { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('canvas'); ctx.drawImage(source, 0, 0, width, height); return canvas; } /** * PDF 原样(仅拦 10MB);图片压成 JPEG,尽量落在 8MB 以内。 */ export async function prepareSupplierInvoiceFile(file: File): Promise { if (!isSupplierInvoiceFile(file)) { throw new Error('unsupported'); } if (isSupplierInvoicePdf(file)) { if (file.size > SUPPLIER_INVOICE_MAX_BYTES) { throw new Error('too_large'); } return file; } if (file.size <= COMPRESS_TARGET_BYTES) { return file; } try { const source = await loadOrientedCanvasFromFile(file); let width = source.width; let height = source.height; const maxDim = Math.max(width, height); if (maxDim > MAX_DIMENSION) { const scale = MAX_DIMENSION / maxDim; width = Math.max(1, Math.round(width * scale)); height = Math.max(1, Math.round(height * scale)); } let canvas = scaleCanvas(source, width, height); for (const quality of [0.82, 0.7, 0.55, 0.4]) { const out = dataUrlToJpegFile(canvas.toDataURL('image/jpeg', quality), file.name); if (out.size <= COMPRESS_TARGET_BYTES) return out; } canvas = scaleCanvas(source, Math.max(1, Math.round(width * 0.5)), Math.max(1, Math.round(height * 0.5))); const last = dataUrlToJpegFile(canvas.toDataURL('image/jpeg', 0.4), file.name); if (last.size > SUPPLIER_INVOICE_MAX_BYTES) { throw new Error('too_large'); } return last; } catch (error) { if (error instanceof Error && (error.message === 'too_large' || error.message === 'unsupported')) { throw error; } if (file.size <= SUPPLIER_INVOICE_MAX_BYTES) return file; throw new Error('too_large'); } }