The following approach covers how to convert PNG to JPG in Node.js using Jimp module. Jimp is an image processing library that we can use to do a lot of operations on images. Jimp stands for JavaScript Image Manipulation Program.
Approach
To convert PNG to JPG using Node.js. We will
- Import Jimp module in our application.
- Read PNG image in Jimp module.
- Resize or modify if needed.
- Save the image as JPG usingĀ
.write()Ā method. - Return the final JPG Image.
Steps to Convert PNG to JPG using Node.js
Step 1: Initialize node.js project with the following command.
npm initStep 2: Install the required module using the following command.
npm install jimpupdated dependencies in package.json file
"dependencies": {
"jimp": "^0.22.12",
}
Step 3: Get one sample PNG file, for this example, we have taken the below image and placed it in the static folder.
Project Structure:
Step 4: Create an index.js file with the following code.
// 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");
});
Step 5: Run node.js project using the following command.
node index.jsOutput: See the JPG output in the output folder.