Refactor encoding constants
This commit is contained in:
parent
4ffad01bbe
commit
e8988e0e4c
|
@ -19,12 +19,17 @@ const IMAGES_DESTINATION_DIRECTORY = "public/images";
|
||||||
|
|
||||||
void optimizeImages();
|
void optimizeImages();
|
||||||
|
|
||||||
|
const IMAGE_ENCODE_OPTIONS = { mozjpeg: {} };
|
||||||
|
const GET_ENCODER_FROM_EXTENSION: { [imageExtension: string]: string } = {
|
||||||
|
jpg: "mozjpeg",
|
||||||
|
jpeg: "mozjpeg",
|
||||||
|
};
|
||||||
|
|
||||||
export async function optimizeImages() {
|
export async function optimizeImages() {
|
||||||
const imagePaths = await getFilePathsInDirectory(IMAGES_SOURCE_DIRECTORY);
|
const imagePaths = await getFilePathsInDirectory(IMAGES_SOURCE_DIRECTORY);
|
||||||
await fse.emptyDir(IMAGES_DESTINATION_DIRECTORY);
|
await fse.emptyDir(IMAGES_DESTINATION_DIRECTORY);
|
||||||
|
|
||||||
const imagePool = new ImagePool(cpus().length);
|
const imagePool = new ImagePool(cpus().length);
|
||||||
const encodeOptions = { mozjpeg: {} };
|
|
||||||
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
imagePaths.map(async (imagePath) => {
|
imagePaths.map(async (imagePath) => {
|
||||||
|
@ -33,9 +38,9 @@ export async function optimizeImages() {
|
||||||
IMAGES_DESTINATION_DIRECTORY,
|
IMAGES_DESTINATION_DIRECTORY,
|
||||||
imagePath
|
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);
|
await fse.copy(sourcePath, destinationPath);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -44,10 +49,12 @@ export async function optimizeImages() {
|
||||||
const ingestedImage = imagePool.ingestImage(rawImageFile);
|
const ingestedImage = imagePool.ingestImage(rawImageFile);
|
||||||
|
|
||||||
await ingestedImage.decoded;
|
await ingestedImage.decoded;
|
||||||
await ingestedImage.encode(encodeOptions);
|
await ingestedImage.encode(IMAGE_ENCODE_OPTIONS);
|
||||||
|
|
||||||
const encodedImage = (await ingestedImage.encodedWith.mozjpeg).binary;
|
const encodedImage = await ingestedImage.encodedWith[
|
||||||
await fse.outputFile(destinationPath, encodedImage);
|
GET_ENCODER_FROM_EXTENSION[fileExtension]
|
||||||
|
];
|
||||||
|
await fse.outputFile(destinationPath, encodedImage.binary);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue