pay
This commit is contained in:
@@ -57,3 +57,42 @@ async function optimizeImageFile(filePath, { maxDimension = DEFAULT_MAX_DIMENSIO
|
||||
}
|
||||
|
||||
module.exports = { optimizeImageFile, DEFAULT_MAX_DIMENSION, DEFAULT_JPEG_QUALITY }
|
||||
|
||||
const VARIANT_WIDTHS = [480, 800]
|
||||
|
||||
/**
|
||||
* نسخههای کوچکتر (WebP، با حفظ نسبت تصویر) کنار فایل اصلی میسازد و یک placeholder
|
||||
* خیلی کمحجم هم میسازد. فایل اصلی دستنخورده میماند و نسخهای که از اصل بزرگتر
|
||||
* نباشد ساخته نمیشود.
|
||||
*/
|
||||
async function generateImageVariants(filePath, { widths = VARIANT_WIDTHS } = {}) {
|
||||
if (!filePath) return
|
||||
try {
|
||||
if (!(await fs.pathExists(filePath))) return
|
||||
const metadata = await sharp(filePath, { failOn: 'none' }).metadata()
|
||||
if (!metadata.width || !metadata.height) return
|
||||
|
||||
const dir = path.dirname(filePath)
|
||||
const base = path.basename(filePath, path.extname(filePath))
|
||||
const source = sharp(filePath, { failOn: 'none' }).rotate()
|
||||
|
||||
for (const width of widths) {
|
||||
if (width >= metadata.width) continue
|
||||
await source
|
||||
.clone()
|
||||
.resize({ width, fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 80 })
|
||||
.toFile(path.join(dir, `${base}.w${width}.webp`))
|
||||
}
|
||||
|
||||
await source
|
||||
.clone()
|
||||
.resize({ width: 24, fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 40 })
|
||||
.toFile(path.join(dir, `${base}.lqip.webp`))
|
||||
} catch (error) {
|
||||
console.error('[imageOptimize] variants failed:', error.message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.generateImageVariants = generateImageVariants
|
||||
|
||||
Reference in New Issue
Block a user