71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import fs from "fs-extra";
|
|
|
|
import dotenv from "dotenv";
|
|
import ft from "file-type";
|
|
import core from "file-type/core";
|
|
import gm from "gm";
|
|
import path, { resolve } from "path";
|
|
import { logger } from "../server";
|
|
import { FolderPaths } from "./serverInit";
|
|
|
|
//const heicConverter = require("heic-convert");
|
|
var imageMagick = gm.subClass({ imageMagick: true });
|
|
|
|
//gm.subClass();
|
|
dotenv.config({
|
|
path: resolve(process.cwd(), `.env.${process.env.NODE_ENV || "development"}`),
|
|
});
|
|
|
|
export async function ConvertHeicFiles(files: Express.Multer.File[]) {
|
|
for (const file of files) {
|
|
const type: core.FileTypeResult | undefined = await ft.fromFile(file.path);
|
|
if (type?.mime === "image/heic") {
|
|
logger.log(
|
|
"debug",
|
|
`Converting ${file.filename} image to JPEG from HEIC.`
|
|
);
|
|
const convertedFileName = `${
|
|
path.parse(path.basename(file.originalname)).name
|
|
}-${Math.floor(Date.now() / 1000)}.jpeg`;
|
|
|
|
await ConvertToJpeg(
|
|
file.path,
|
|
`${file.destination}/${convertedFileName}`
|
|
);
|
|
//Move the HEIC.
|
|
if (process.env.KEEP_CONVERTED_ORIGINALS) {
|
|
await fs.ensureDir(
|
|
path.join(file.destination, FolderPaths.ConvertedOriginalSubDir)
|
|
);
|
|
await fs.move(
|
|
file.path,
|
|
`${path.join(
|
|
file.destination,
|
|
FolderPaths.ConvertedOriginalSubDir
|
|
)}/${file.filename}`
|
|
);
|
|
} else {
|
|
await fs.unlink(file.destination);
|
|
}
|
|
//Update the multer file entry.
|
|
|
|
file.filename = convertedFileName;
|
|
file.mimetype = "image/jpeg";
|
|
file.path = `${file.destination}/${convertedFileName}`;
|
|
}
|
|
}
|
|
}
|
|
|
|
async function ConvertToJpeg(file: string, newPath: string) {
|
|
const fileOnDisk: Buffer = await fs.readFile(file);
|
|
|
|
return new Promise<string>((resolve, reject) => {
|
|
const result = imageMagick(fileOnDisk)
|
|
.setFormat("jpg")
|
|
.write(newPath, (error) => {
|
|
if (error) reject(error.message);
|
|
resolve(newPath);
|
|
});
|
|
});
|
|
}
|