|
| 1 | +const sharp = require('sharp'); |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | + |
| 5 | +const imageDir = './public/images'; |
| 6 | +const extensions = ['.png', '.jpg', '.jpeg']; |
| 7 | + |
| 8 | +async function convertImages(dir) { |
| 9 | + if (!fs.existsSync(dir)) { |
| 10 | + console.log(`Directory ${dir} does not exist`); |
| 11 | + return; |
| 12 | + } |
| 13 | + |
| 14 | + const files = fs.readdirSync(dir); |
| 15 | + |
| 16 | + for (const file of files) { |
| 17 | + const filePath = path.join(dir, file); |
| 18 | + const stat = fs.statSync(filePath); |
| 19 | + |
| 20 | + if (stat.isDirectory()) { |
| 21 | + await convertImages(filePath); |
| 22 | + continue; |
| 23 | + } |
| 24 | + |
| 25 | + const ext = path.extname(file).toLowerCase(); |
| 26 | + if (!extensions.includes(ext)) continue; |
| 27 | + |
| 28 | + const baseName = path.basename(file, ext); |
| 29 | + const webpPath = path.join(dir, `${baseName}.webp`); |
| 30 | + const avifPath = path.join(dir, `${baseName}.avif`); |
| 31 | + |
| 32 | + try { |
| 33 | + // 转换为 WebP |
| 34 | + if (!fs.existsSync(webpPath)) { |
| 35 | + await sharp(filePath) |
| 36 | + .webp({ quality: 85 }) |
| 37 | + .toFile(webpPath); |
| 38 | + console.log(`✅ Created: ${webpPath}`); |
| 39 | + } |
| 40 | + |
| 41 | + // 转换为 AVIF |
| 42 | + if (!fs.existsSync(avifPath)) { |
| 43 | + await sharp(filePath) |
| 44 | + .avif({ quality: 80 }) |
| 45 | + .toFile(avifPath); |
| 46 | + console.log(`✅ Created: ${avifPath}`); |
| 47 | + } |
| 48 | + } catch (error) { |
| 49 | + console.error(`❌ Error converting ${filePath}:`, error.message); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +console.log('🚀 Starting image conversion...'); |
| 55 | +convertImages(imageDir).then(() => { |
| 56 | + console.log('✅ All images converted!'); |
| 57 | +}).catch(error => { |
| 58 | + console.error('❌ Conversion failed:', error); |
| 59 | + process.exit(1); |
| 60 | +}); |
0 commit comments