如何使用 Node.js 将 PNG 转换为 JPG?
以下方法介绍了如何在 Node.js 中使用Jimp模块将 PNG 转换为 JPG。 Jimp 是一个图像处理库,我们可以使用它对图像进行大量操作。 Jimp 代表 JavaScript 图像处理程序。
方法:我们将使用以下步骤:
- 在我们的应用程序中导入Jimp模块。
- 在 Jimp 模块中读取 PNG 图像。
- 使用 Jimp 功能将 PNG 转换为 JPG。
- 返回最终的 JPG 图像。
设置环境和执行:
第 1 步:使用以下命令初始化 node.js 项目。
npm init
第 2 步:使用以下命令安装所需的模块。
npm install jimp
第 3 步:获取一个示例 PNG 文件,在此示例中,我们将下图放在静态文件夹中。
项目结构:它应该如下所示:
第 4 步:使用以下代码创建一个index.js文件。
index.js
// Import jimp module
const Jimp = require("jimp");
// Read the PNG file and convert it to editable format
Jimp.read("./static/GFG_IMG.png", function (err, image) {
if (err) {
// Return if any error
console.log(err);
return;
}
// Convert image to JPG and store it to
// './output/' folder with 'out.jpg' name
image.write("./output/out.jpg");
});
第 5 步:使用以下命令运行 node.js 项目。
node index.js
输出:查看输出文件夹中的 JPG 输出。