Open In App

How to convert JPG to PNG using Node.js ?

Last Updated : 25 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Converting images between different formats is a common requirement in web development. Node.js, with its powerful libraries and ecosystem, makes it easy to perform such tasks. This article will show you how to convert a JPG image to PNG using Node.js, covering both the basic and more advanced techniques.

Approach

To convert JPG to PNG using Node.js with Jimp

  • Install Jimp package via npm
  • Use Jimp to read the JPG file.
  • Resize or modify if needed.
  • Save the image as PNG using .write() method.

Jimp (JavaScript Image Manipulation Program)

Jimp is a JavaScript image processing library that is used with Node. We will use Jimp for converting JPG to PNG. To install Jimp in our project, we just need to install its npm module by executing the following line in our terminal.

Installation:

npm install --save jimp

Usage:

To use it in our project, we will need to import the package into our index.js file by using the following line of code. Now that we have Jimp installed and ready to use, we can move ahead to convert JPG to PNG.

const Jimp = require("jimp");

JPG to PNG Conversion

We will use the .read() and .write() methods to perform the conversion. Let's consider an example where we have an input JPG image and then convert it to a PNG image.

Example: Let's suppose we have a JPG image given below as input.

gfg.jpg

Example: Example to convert above image into PNG format, our script code will look like the following

JavaScript
// 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")
  }
})

On executing the code using node, we should be able to get the PNG converted image in our images folder as shown below.

Output:


Next Article

Similar Reads