Sling Academy
Home/Node.js/Node.js: How to convert PNG to JPG and vice versa

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

Last updated: December 31, 2023

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.

Next Article: How to Write a Telegram Bot with Node.js

Previous Article: Node.js: How to convert images to byte arrays

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates