Open In App

How to convert PNG to JPG using Node.js ?

Last Updated : 23 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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: We will use the following steps:

  1. Import Jimp module in our application.
  2. Read PNG image in Jimp module.
  3. Convert PNG to JPG using Jimp functionalities.
  4. Return the final JPG Image.

Setting up environment and Execution:

Step 1: Initialize node.js project with the following command.

npm init

Step 2: Install the required module using the following command.

npm install jimp

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: It should look like the following:

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.js

Output: See the JPG output in the output folder.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads