Skip to content
On this page
js
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');

// 图片列表
const imageFiles = [
    'xxx.webp'
];

// 目标比例 16:9
const targetAspectRatio = 16 / 9;

// 创建输出目录
const outputDir = 'output_images';

// 检查并创建输出目录
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir);
}

imageFiles.forEach(imageFile => {
  sharp(imageFile)
    .metadata()
    .then(({ width, height }) => {
      console.log(`处理图片: ${imageFile}, 原图尺寸: 宽度=${width}, 高度=${height}`);

      // 计算裁剪区域
      let cropWidth, cropHeight, left, top;

      // 如果宽度/高度大于目标比例,裁剪高度
      if (width / height > targetAspectRatio) {
        cropHeight = height;
        cropWidth = Math.floor(height * targetAspectRatio);
        left = Math.floor((width - cropWidth) / 2);
        top = 0;
      } else {
        cropWidth = width;
        cropHeight = Math.floor(width / targetAspectRatio);
        left = 0;
        top = Math.floor((height - cropHeight) / 2);
      }

      console.log(`裁剪区域: 宽度=${cropWidth}, 高度=${cropHeight}, left=${left}, top=${top}`);

      // 获取不带扩展名的文件名
      const outputFileName = path.basename(imageFile, path.extname(imageFile)) + '_cropped.jpg';

      // 生成完整的输出文件路径,放到 output_images 目录下
      const outputFilePath = path.join(outputDir, outputFileName);

      // 裁剪并调整为目标尺寸 640x360
      return sharp(imageFile)
        .extract({ width: cropWidth, height: cropHeight, left: left, top: top })
        .resize(640, 360) // 将裁剪后的图片调整为 640x360
        .toFile(outputFilePath); // 保存到新目录中
    })
    .then(() => {
      console.log(`图片 ${imageFile} 裁剪并调整为 640x360 完成,保存到 ${outputDir}`);
    })
    .catch(err => {
      console.error(`处理图片 ${imageFile} 时发生错误:`, err);
    });
});