Refactor encoding constants
This commit is contained in:
parent
4ffad01bbe
commit
e8988e0e4c
|
@ -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);
|
||||
})
|
||||
);
|
||||
|
||||
|
|
Loading…
Reference in New Issue