以下方法介紹了如何在 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 輸出。
相關用法
- Python PNG轉JPG用法及代碼示例
- Node.js JPG轉PNG用法及代碼示例
- Node.js GM solarize()用法及代碼示例
- Node.js MySQL Max()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- PHP stdClass()用法及代碼示例
注:本文由純淨天空篩選整理自pratikraut0000大神的英文原創作品 How to convert PNG to JPG using Node.js ?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。