40 lines
1.4 KiB
JavaScript
40 lines
1.4 KiB
JavaScript
/**
|
|
* Convertit un fichier HEIC/HEIF en Blob JPEG.
|
|
* @param {File} file
|
|
* @returns {Promise<Blob>}
|
|
* @throws {TypeError} si l'entrée n'est pas un fichier HEIC/HEIF
|
|
* @throws {Error} si la conversion échoue ou dépasse 30s
|
|
*/
|
|
export async function convertHeicToJpeg(file) {
|
|
if (!(file instanceof File)) {
|
|
throw new TypeError("L'entrée doit être un objet File");
|
|
}
|
|
// Certains iPhone envoient un type MIME vide pour les HEIC — on l'autorise
|
|
const type = file.type.toLowerCase();
|
|
if (type !== '' && !['image/heic', 'image/heif'].includes(type)) {
|
|
throw new TypeError(`Format attendu : HEIC/HEIF. Reçu : ${file.type || '(vide)'}`);
|
|
}
|
|
|
|
console.log(`[heicConverter] Début conversion : ${file.name} (${file.type || 'type vide'}, ${(file.size/1024).toFixed(0)} Ko)`);
|
|
|
|
const timeout = new Promise((_, reject) =>
|
|
setTimeout(() => reject(new Error('Timeout : conversion > 30s. Vérifiez que le fichier est bien un HEIC valide.')), 30_000)
|
|
);
|
|
|
|
const conversion = heic2any({
|
|
blob: file,
|
|
toType: 'image/jpeg',
|
|
quality: 0.92,
|
|
});
|
|
|
|
const result = await Promise.race([conversion, timeout]);
|
|
|
|
const blob = Array.isArray(result) ? result[0] : result;
|
|
if (!(blob instanceof Blob)) {
|
|
throw new Error("heic2any n'a pas retourné un Blob");
|
|
}
|
|
|
|
console.log(`[heicConverter] ✅ Conversion réussie : ${file.name} → ${(blob.size/1024).toFixed(0)} Ko`);
|
|
return blob;
|
|
}
|