用 JavaScript 脚本批量裁剪 PNG 图片并导出固定分辨率
```javascript const fs = require('fs'); const sharp = require('sharp'); // 定义输入文件夹和输出文件夹的路径 const inputFolder = 'yourInputFolderPath'; const outputFolder = 'yourOutputFolderPath'; // 读取输入文件夹中的所有 PNG 图片 fs.readdir(inputFolder, (err, files) => { if (err) { console.error('Error reading directory:', err); return; } files.forEach(file => { if (file.endsWith('.png')) { // 读取图片 sharp(`${inputFolder}/${file}`) .metadata() .then(metadata => { // 计算裁剪的尺寸 const width = metadata.width; const height = metadata.height; const newWidth = Math.min(width, height); const newHeight = Math.min(width, height); // 进行裁剪 sharp(`${inputFolder}/${file}`) .extract({ left: 0, top: 0, width: newWidth, height: newHeight }) .resize(300, 300) .toFile(`${outputFolder}/${file}`, (err, info) => { if (err) { console.error('Error processing image:', err); } else { console.log(`Processed ${file} successfully`); } }); }); } }); }); // 额外注意的逻辑点: // 1. 确保输入和输出文件夹路径的正确性。 // 2. 处理可能出现的文件读取或写入错误。 // 3. 测试代码在不同尺寸和内容的图片上的效果。 ``` ######[AI写代码神器 | 385点数解答 | 2025-01-12 20:42:44]
- 超详细!用复杂 HTML 代码打造功能丰富网站,含特色搜索与展示(字节豆包 | 572点数解答 | 2024-11-17 07:58:26)273
- Java调用Python方法:含if __name__判断的实现及代码示例 (讯飞星火 | 336点数解答 | 2024-06-07 16:33:41)330
- 巧用 CSS 和 HTML:在公园背景中精准种植五棵间距一致的树(GPT | 494点数解答 | 2024-10-03 19:44:51)190
- 优化用户登录代码:输入验证、按钮禁用与样式优化全解析(字节豆包 | 1402点数解答 | 2025-03-18 21:31:12)200
- 尘寰异世:中式恐怖风格下的诡异道士与角色奇幻之旅(DeepSeek | 2006点数解答 | 2025-07-30 21:26:41)168
- 因仅图片链接信息难以明确核心要点,以下标题供参考:“神秘图片背后隐藏着怎样的秘密?” (字节豆包 | 52点数解答 | 2025-10-17 21:07:19)79
- 工程师必知!LoadRunner 脚本调试的 10 大基本步骤(百度文心 | 463点数解答 | 2023-11-09 18:25:48)343
- JMeter 工程师必知:HTTP 代理服务器原理及脚本录制全流程揭秘(百度文心 | 371点数解答 | 2023-11-09 18:26:54)281
- Linux脚本:巧用if条件精准判断/home/test.txt文件是否存在(阿里通义 | 356点数解答 | 2024-11-16 16:42:28)295
- Linux 脚本:轻松判断 /home/test.txt 文件是否存在及更多检查选项(讯飞星火 | 347点数解答 | 2024-11-16 16:45:35)270
- Photoshop 脚本:一键为选定图层增加颜色,代码详解与注意事项! (DeepSeek | 303点数解答 | 2025-03-11 14:42:50)266
- 用 Python 脚本实现类似 Photoshop 增加颜色效果,代码示例来了!(字节豆包 | 260点数解答 | 2025-03-11 14:43:16)249