|
| 1 | +/** |
| 2 | + * HEIC/HEIF image detection and conversion utilities. |
| 3 | + * Uses libheif-js (WASM) for client-side decoding. |
| 4 | + */ |
| 5 | + |
| 6 | +const HEIC_EXTENSIONS = ['.heic', '.heif'] |
| 7 | +const HEIC_MIME_TYPES = ['image/heic', 'image/heif', 'image/heic-sequence', 'image/heif-sequence'] |
| 8 | + |
| 9 | +/** |
| 10 | + * Detect if a file is HEIC/HEIF by MIME type, extension, or magic bytes. |
| 11 | + */ |
| 12 | +export async function isHeicFile(file: File): Promise<boolean> { |
| 13 | + if (HEIC_MIME_TYPES.includes(file.type.toLowerCase())) { |
| 14 | + return true |
| 15 | + } |
| 16 | + |
| 17 | + const ext = '.' + file.name.split('.').pop()?.toLowerCase() |
| 18 | + if (HEIC_EXTENSIONS.includes(ext)) { |
| 19 | + return true |
| 20 | + } |
| 21 | + |
| 22 | + // Check magic bytes: ftyp box at offset 4 |
| 23 | + try { |
| 24 | + const slice = file.slice(0, 12) |
| 25 | + const buffer = await slice.arrayBuffer() |
| 26 | + const header = new Uint8Array(buffer) |
| 27 | + if (header.length >= 12) { |
| 28 | + const ftyp = String.fromCharCode(header[4], header[5], header[6], header[7]) |
| 29 | + if (ftyp === 'ftyp') { |
| 30 | + const brand = String.fromCharCode(header[8], header[9], header[10], header[11]) |
| 31 | + if (['heic', 'heix', 'mif1', 'heif'].includes(brand)) { |
| 32 | + return true |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + } catch { |
| 37 | + // Can't read file — fall through |
| 38 | + } |
| 39 | + |
| 40 | + return false |
| 41 | +} |
| 42 | + |
| 43 | +interface HeifImage { |
| 44 | + get_width(): number |
| 45 | + get_height(): number |
| 46 | + display(imageData: ImageData, callback: (result: ImageData) => void): void |
| 47 | +} |
| 48 | + |
| 49 | +interface HeifDecoder { |
| 50 | + decode(data: Uint8Array): HeifImage[] |
| 51 | +} |
| 52 | + |
| 53 | +interface LibHeif { |
| 54 | + HeifDecoder: new () => HeifDecoder |
| 55 | +} |
| 56 | + |
| 57 | +let libheifInstance: LibHeif | null = null |
| 58 | + |
| 59 | +async function getLibHeif(): Promise<LibHeif> { |
| 60 | + if (libheifInstance) return libheifInstance |
| 61 | + const module = await import('libheif-js') |
| 62 | + libheifInstance = module.default || module |
| 63 | + return libheifInstance! |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Convert a HEIC/HEIF file to JPEG using libheif-js WASM decoder. |
| 68 | + */ |
| 69 | +export async function convertHeicToJpeg(file: File, quality = 0.92): Promise<File> { |
| 70 | + const libheif = await getLibHeif() |
| 71 | + const buffer = await file.arrayBuffer() |
| 72 | + const data = new Uint8Array(buffer) |
| 73 | + |
| 74 | + const decoder = new libheif.HeifDecoder() |
| 75 | + const images = decoder.decode(data) |
| 76 | + |
| 77 | + if (!images || images.length === 0) { |
| 78 | + throw new Error(`Failed to decode HEIC file: ${file.name}`) |
| 79 | + } |
| 80 | + |
| 81 | + const image = images[0] |
| 82 | + const width = image.get_width() |
| 83 | + const height = image.get_height() |
| 84 | + |
| 85 | + const canvas = document.createElement('canvas') |
| 86 | + canvas.width = width |
| 87 | + canvas.height = height |
| 88 | + const ctx = canvas.getContext('2d') |
| 89 | + if (!ctx) throw new Error('Could not create canvas context') |
| 90 | + |
| 91 | + const imageData = ctx.createImageData(width, height) |
| 92 | + |
| 93 | + await new Promise<void>((resolve, reject) => { |
| 94 | + try { |
| 95 | + image.display(imageData, (displayData: ImageData) => { |
| 96 | + if (!displayData) { |
| 97 | + reject(new Error(`Failed to render HEIC image: ${file.name}`)) |
| 98 | + return |
| 99 | + } |
| 100 | + ctx.putImageData(displayData, 0, 0) |
| 101 | + resolve() |
| 102 | + }) |
| 103 | + } catch (err) { |
| 104 | + reject(err) |
| 105 | + } |
| 106 | + }) |
| 107 | + |
| 108 | + const blob = await new Promise<Blob>((resolve, reject) => { |
| 109 | + canvas.toBlob( |
| 110 | + (b) => (b ? resolve(b) : reject(new Error('Canvas toBlob failed'))), |
| 111 | + 'image/jpeg', |
| 112 | + quality |
| 113 | + ) |
| 114 | + }) |
| 115 | + |
| 116 | + const newName = file.name.replace(/\.(heic|heif)$/i, '.jpg') |
| 117 | + return new File([blob], newName, { type: 'image/jpeg' }) |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Process files, converting any HEIC/HEIF to JPEG. Returns converted files |
| 122 | + * and any errors that occurred during conversion. |
| 123 | + */ |
| 124 | +export async function processFilesForHeic( |
| 125 | + files: File[], |
| 126 | +): Promise<{ converted: File[]; errors: Array<{ fileName: string; error: string }> }> { |
| 127 | + const heicFlags = await Promise.all(files.map(isHeicFile)) |
| 128 | + const hasHeic = heicFlags.some(Boolean) |
| 129 | + |
| 130 | + if (!hasHeic) { |
| 131 | + return { converted: files, errors: [] } |
| 132 | + } |
| 133 | + |
| 134 | + const converted: File[] = [] |
| 135 | + const errors: Array<{ fileName: string; error: string }> = [] |
| 136 | + |
| 137 | + for (let i = 0; i < files.length; i++) { |
| 138 | + if (!heicFlags[i]) { |
| 139 | + converted.push(files[i]) |
| 140 | + continue |
| 141 | + } |
| 142 | + |
| 143 | + try { |
| 144 | + converted.push(await convertHeicToJpeg(files[i])) |
| 145 | + } catch (err) { |
| 146 | + errors.push({ |
| 147 | + fileName: files[i].name, |
| 148 | + error: err instanceof Error ? err.message : 'Unknown conversion error', |
| 149 | + }) |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + return { converted, errors } |
| 154 | +} |
0 commit comments