Convert jpg to png in Nodejs

Webstorm Visual Studio Code

To convert a JPEG image (.jpg format) to a PNG image (.png format) in Node.js, you can use a library like sharp. Here's an example of how you can do it:

First, you'll need to install the sharp library:

npm install sharp

Then, you can use the following code to convert a JPG image to PNG:


const sharp = require('sharp');

// Input and output file paths
const inputFilePath = 'input.jpg';
const outputFilePath = 'output.png';

// Convert JPG to PNG
sharp(inputFilePath)
  .png()
  .toFile(outputFilePath, (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`Image converted: ${outputFilePath}`);
    }
  });

Require the sharp library. Specify the file paths for the input (JPEG) and output (PNG) files. Use sharp(inputFilePath) to read the input JPEG file. Use .png() to specify that you want to convert it to a PNG format. Use .toFile(outputFilePath, callback) to save the converted image to the specified output file. Make sure to replace 'input.jpg' and 'output.png' with the actual paths to your input and output files.

Keep in mind that sharp is a powerful image processing library, and it provides many other options and features. This example demonstrates a basic conversion, but you can explore the library's documentation for more advanced usage.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • Nodejs 18