Refactor encoding constants

This commit is contained in:
Amy 2021-10-14 23:32:38 -04:00
parent 4ffad01bbe
commit e8988e0e4c
1 changed files with 13 additions and 6 deletions

View File

@ -19,12 +19,17 @@ const IMAGES_DESTINATION_DIRECTORY = "public/images";
void optimizeImages();
const IMAGE_ENCODE_OPTIONS = { mozjpeg: {} };
const GET_ENCODER_FROM_EXTENSION: { [imageExtension: string]: string } = {
jpg: "mozjpeg",
jpeg: "mozjpeg",
};
export async function optimizeImages() {
const imagePaths = await getFilePathsInDirectory(IMAGES_SOURCE_DIRECTORY);
await fse.emptyDir(IMAGES_DESTINATION_DIRECTORY);
const imagePool = new ImagePool(cpus().length);
const encodeOptions = { mozjpeg: {} };
await Promise.all(
imagePaths.map(async (imagePath) => {
@ -33,9 +38,9 @@ export async function optimizeImages() {
IMAGES_DESTINATION_DIRECTORY,
imagePath
);
const fileExtension = imagePath.split(".").pop();
const fileExtension = imagePath.split(".").pop() ?? "";
if (!(fileExtension === "jpg" || fileExtension === "jpeg")) {
if (!GET_ENCODER_FROM_EXTENSION[fileExtension]) {
await fse.copy(sourcePath, destinationPath);
return;
}
@ -44,10 +49,12 @@ export async function optimizeImages() {
const ingestedImage = imagePool.ingestImage(rawImageFile);
await ingestedImage.decoded;
await ingestedImage.encode(encodeOptions);
await ingestedImage.encode(IMAGE_ENCODE_OPTIONS);
const encodedImage = (await ingestedImage.encodedWith.mozjpeg).binary;
await fse.outputFile(destinationPath, encodedImage);
const encodedImage = await ingestedImage.encodedWith[
GET_ENCODER_FROM_EXTENSION[fileExtension]
];
await fse.outputFile(destinationPath, encodedImage.binary);
})
);