JPG 和 PNG 都是廣泛使用的圖像格式。使用這些格式允許用戶包含和使用數字圖像。在本文中,我們將討論如何使用 Node.js 將給定的 JPG 圖像轉換為 PNG 圖像,這有助於在我們的 Web 應用程序中使用該圖像。
Jimp(JavaScript 圖像處理程序):
Jimp 是一個完全用 JavaScript 編寫並由 Node.js 使用的圖像處理庫。對於 JPG 到 PNG 的轉換,我們將使用 Jimp。
安裝:
要在我們的項目中安裝 Jimp,我們隻需將其 npm 模塊安裝到我們的項目中。這可以通過在我們的終端中執行以下行來完成。
npm install --save jimp
用法:
要在我們的項目中使用它,我們需要使用以下代碼行將包導入到我們的 index.js 文件中。
const Jimp = require("jimp");
現在我們已經安裝並準備好使用 Jimp,我們可以繼續將 JPG 轉換為 PNG。
JPG到PNG轉換:
我們將使用 .read() 和 .write() 方法進行轉換。讓我們考慮一個示例,我們將輸入 JPG 圖像,然後將其轉換為 PNG 圖像。
例:
假設我們有一個下麵給出的 JPG 圖像作為輸入。

gfg.jpg
我們將代碼保存在 images 文件夾中。現在要將其轉換為 PNG 格式,我們的腳本代碼將如下所示。
index.js
// Importing the jimp module
const Jimp= require("jimp");
//We will first read the JPG image using read() method.
Jimp.read("images/gfg.jpg", function (err, image) {
//If there is an error in reading the image,
//we will print the error in our terminal
if (err) {
console.log(err)
}
//Otherwise we convert the image into PNG format
//and save it inside images folder using write() method.
else {
image.write("images/gfg.png")
}
})
在使用 node 執行代碼時,我們應該能夠在我們的 images 文件夾中獲得 PNG 轉換後的圖像,如下所示。
輸出:
相關用法
- Python PNG轉JPG用法及代碼示例
- Node.js PNG轉JPG用法及代碼示例
- Node.js GM solarize()用法及代碼示例
- Node.js MySQL Max()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- PHP stdClass()用法及代碼示例
注:本文由純淨天空篩選整理自greenblade29大神的英文原創作品 How to convert JPG to PNG using Node.js ?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。