38 lines
1.1 KiB
JavaScript
38 lines
1.1 KiB
JavaScript
import sharp from "sharp";
|
|
import fs from "fs";
|
|
import path from "path";
|
|
|
|
export async function compressImages(inputPath) {
|
|
const images = fs.readdirSync(inputPath).filter(f => /\.(jpe?g|png)$/i.test(f));;
|
|
|
|
const bufferMap = {};
|
|
await Promise.all(
|
|
images.map(async (image) => {
|
|
const inputImagePath = path.join(inputPath, image);
|
|
// Compress the image (adjust quality for JPEG)
|
|
const buffer = await sharp(inputImagePath)
|
|
.resize({ width: 700 }) // optional resize
|
|
.jpeg({ quality: 70 }) // lower quality = higher compression
|
|
.rotate()
|
|
.toBuffer();
|
|
bufferMap[image] = buffer;
|
|
}),
|
|
);
|
|
return bufferMap;
|
|
}
|
|
|
|
export async function bufferImages(inputPath) {
|
|
const images = fs.readdirSync(inputPath).filter(f => /\.(jpe?g|png)$/i.test(f));;
|
|
|
|
const bufferMap = {};
|
|
await Promise.all(
|
|
images.map(async (image) => {
|
|
const inputImagePath = path.join(inputPath, image);
|
|
// Compress the image (adjust quality for JPEG)
|
|
const buffer = await fs.promises.readFile(inputImagePath);
|
|
bufferMap[image] = buffer;
|
|
}),
|
|
);
|
|
return bufferMap;
|
|
}
|