酷代码 AI
菜单
服务商

我现在要写一个ps的javascript脚本代码,一批png图片,图像内容和图片大小不同,我们需要把图片裁剪掉多余尺寸,并导出图像内容的大小的图片,保持分辨率是300像素。编程过程可以是选择打开的文件夹图片,对图像形成选曲,使用裁剪工具进行裁剪,然后存储为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. 测试代码在不同尺寸和内容的图片上的效果。 ``` [2025-01-12 20:42:44 | AI写代码神器 | 385点数解答]

相关提问
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]