Node.js: How to convert PNG to JPG and vice versa

Updated: December 31, 2023 By: Guest Contributor Post a comment

Learn how to effortlessly convert image formats between PNG and JPG in Node.js using sharp library, complete with code examples to guide you every step of the way.

Before diving into the image conversion tutorial, ensure you have Node.js installed on your system. Familiarity with JavaScript and basic command line usage will also be helpful.

Getting Started with Sharp

Sharp is a high-performance Node.js library for image processing. Install it using npm:

npm install sharp

Converting PNG to JPG

Let’s start by converting a PNG image to JPG format. Here’s a simple script using sharp:

const sharp = require('sharp');

sharp('image.png')
  .toFormat('jpg')
  .toFile('image.jpg')
  .then(() => {
    console.log('Conversion complete.');
  })
  .catch(err => {
    console.error('Error occurred:', err);
  });

Converting JPG to PNG

Converting in the opposite direction is equally straightforward as the previous example:

const sharp = require('sharp');

sharp('image.jpg')
  .toFormat('png')
  .toFile('image.png')
  .then(() => {
    console.log('Conversion complete.');
  })
  .catch(err => {
    console.error('Error occurred:', err);
  });

Encoding and Compression

To control the quality of the output JPG, you can use the quality() method:

sharp('image.png')
  .jpeg({ quality: 80 })
  .toFile('image.jpg');

Similarly, to compress a PNG, use the compressionLevel():

sharp('image.jpg')
  .png({ compressionLevel: 9 })
  .toFile('image.png');

Advanced Usage: Batch Conversion

The sharp library can also handle batch processing. Here’s how to convert multiple PNG files to JPG:

const fs = require('fs');
const sharp = require('sharp');

const convertImages = async (files) => {
  for (const file of files) {
    if (file.endsWith('.png')) {
      await sharp(file)
        .toFormat('jpg')
        .toFile(file.replace('.png', '.jpg'));
    }
  }
};

fs.readdir('.', (err, files) => {
  if (err) {
    console.error('Error reading directory:', err);
    return;
  }
  convertImages(files).then(() => {
    console.log('Batch conversion complete.');
  });
});

Error Handling and Optimization

Error handling is necessary when working with files. Always use try-catch blocks in async functions and promise error callbacks in then-catch chains.

To optimize performance, consider using a Node.js stream, especially when working with large images or a large number of files.

Conclusion

Node.js, combined with sharp, offers a robust solution for converting PNG to JPG and vice versa. The examples provided should give you a solid foundation to integrate image conversion into your Node.js applications.