Files
Stackq/src/lib/convert-heic-server.ts
T

40 lines
1.1 KiB
TypeScript

/**
* Server-side HEIC conversion using heic-convert (Node). Use in form actions only.
*/
export function isHeicFile(file: File): boolean {
const name = file.name.toLowerCase();
const type = (file.type ?? "").toLowerCase();
return (
name.endsWith(".heic") ||
name.endsWith(".heif") ||
type === "image/heic" ||
type === "image/heif"
);
}
/**
* If the file is HEIC/HEIF, convert to JPEG and return a new File. Otherwise return the original.
*/
export async function convertHeicFileToJpegIfNeeded(file: File): Promise<File> {
if (!isHeicFile(file)) return file;
const arrayBuffer = await file.arrayBuffer();
const inputBuffer = Buffer.from(arrayBuffer);
const convert = (await import("heic-convert")).default as (opts: {
buffer: Buffer;
format: string;
quality?: number;
}) => Promise<Buffer>;
const outputBuffer = await convert({
buffer: inputBuffer,
format: "JPEG",
quality: 0.92,
});
const baseName = file.name.replace(/\.[^.]+$/i, "") || "image";
return new File([outputBuffer], `${baseName}.jpg`, {
type: "image/jpeg",
lastModified: Date.now(),
});
}