我正在try 使用Tinify Node JS API调整图像大小.我想调整一个目录的文件,而不仅仅是一个单一的文件.这是一个简单的例子.

const source = tinify.fromFile("example.jpg");
const resized = source.resize({
  method: "cover",
  width: 720,
  height: 225
});
resized.toFile("example-small.jpg");

类似地,我想做同样的转换所有文件在一个目录到.webp:

const source = tinify.fromFile("example.jpg");
const converted = source.convert({type:["image/webp","image/png"]});
const extension = converted.result().extension();
extension.then(ext => {
  converted.toFile("example." + ext);
})

我对NodeJS的了解有限,如有帮助将不胜感激,谢谢.

推荐答案

从源目录读取所有文件:利用Node.js中的文件系统模块枚举指定源目录中的所有文件.

调整每个图像的大小:使用Tinify API根据预定义的尺寸调整每个图像的大小,类似于前面描述的方法.

保存已调整大小的图像:将已调整大小的图像存储在指定的目标目录中,保留其原始文件名以便于识别和保持一致性.

这是演示代码.

另存为converts.js文件名

const fs = require("fs");
const path = require("path");
const tinify = require("tinify");
tinify.key = "[ YOUR API KEY ]"; // Replace with your actual API key

const sourceDir = "image/png";
const destDir = "image/webp";

async function resizeAndConvertImages() {
  try {
    const files = fs.readdirSync(sourceDir);

    for (const file of files) {
      const ext = path.extname(file).toLowerCase();
      if (ext === '.png' || ext === '.jpg' || ext === '.jpeg') {
        const sourcePath = path.join(sourceDir, file);
        const destPath = path.join(destDir, file).replace(ext, '.webp'); // Change extension to .webp

        const source = tinify.fromFile(sourcePath);
        const resized = source.resize({
          method: "cover",
          width: 720,
          height: 225
        });

        await resized.toFile(destPath);
        console.log(`${file} has been resized and saved as ${destPath}`);
      }
    }
  } catch (error) {
    console.error("Error during processing:", error);
  }
}

resizeAndConvertImages();

Get API Key

从您的tinify个控制面板

https://tinify.com/dashboard/api

enter image description here

Input directory

It mixed JPG and PNG images enter image description here

enter image description here

Install Dependency

npm install tinify

Run it

node converts.js

enter image description here

Result

enter image description here

由于Tinify的API使用的调整大小方法,某些图像可能会被裁剪或裁剪.

enter image description here

Node.js相关问答推荐

Twilio-获取呼叫录音不起作用的请求

当FastifyJS向客户端发送响应时,apache 不会将其发送给他

从目录中获取所有文件,而不是NodeJS中的单个文件

NPM:无法导入本码模块

Axios TypeError:将循环 struct 转换为 JSON

如何在 require 方法中使用路径与node.js react ?

module.exports=require('other') 和临时变量有什么区别?

kubernetes 上的 nextjs 无法启动

如何为单个 mongo nodejs 驱动程序找到最佳连接池大小

JavaScript & Node - 将图像文件保存到服务器但无法查看

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

Cassandra node.js 驱动程序有替代品吗?

我应该在(Docker)容器中使用 forever/pm2 吗?

Node.JS 中的基本 HTTP 身份验证?

node 应用程序是否有任何独立的 gui 模块

npm install 给出警告,npm audit fix 不起作用

名称类型为 mongoose 的字段

Heroku + Node:找不到模块错误

使用 Mongoose 进行多对多映射

node.js 中的意外保留字导入