Sling Academy
Home/Node.js/Node.js: How to convert images to byte arrays

Node.js: How to convert images to byte arrays

Last updated: December 31, 2023

Overview

This tutorial explains the process of converting images to byte arrays in Node.js, using built-in modules and popular npm packages. It’s a useful technique that enables image manipulation, storage, and transmission in applications.

Before proceeding, ensure that you have Node.js installed on your computer, and you are familiar with Node.js basics and file handling. You should also have npm installed to download the necessary packages.

Reading Images into Buffers

In Node.js, buffet means a temporary storage spot for data that is being moved from one place to another. The Buffer class in Node.js is used to work with binary data. In the context of images, buffers help read images as binary data, which can then be manipulated or saved.

Example 1: Using fs.readFile

const fs = require('fs');

fs.readFile('/path/to/image.jpg', (err, data) => {
  if (err) throw err;
  console.log(data);
});

This code snippet uses the fs.readFile method to read the image file into a buffer.

Example 2: Reading Image with ‘fs.readFileSync’

const fs = require('fs');

let imageBuffer = fs.readFileSync('/path/to/image.jpg');
console.log(imageBuffer);

This example demonstrates synchronous file reading, which might be easier for simple scripts but should be avoided in production due to blocking nature.

Working With Streams

Example 3: Reading Image as a Stream

const fs = require('fs');

let stream = fs.createReadStream('/path/to/image.jpg')
  .on('data', (chunk) => {
    console.log(chunk);
  })
  .on('error', (err) => {
    console.error('Error:', err);
  });

Here, we are using streams to read the image data. This is a non-blocking approach suitable for handling large files or many smaller files efficiently.

Using npm Packages for Conversion

Many packages exist to help with image processing, such as ‘sharp’, ‘jimp’, ‘image-to-base64’.

Example 4: Using ‘sharp’ to Convert an Image to Buffer

const sharp = require('sharp');

sharp('/path/to/image.jpg')
  .toBuffer()
  .then(buffer => {
    console.log(buffer);
  })
  .catch(err => {
    console.error('Error:', err);
  });

‘sharp’ provides a fluent interface to convert images to buffers and supports various image formats and operations.

Example 5: Using ‘jimp’ for Buffer Conversion

const Jimp = require('jimp');

Jimp.read('/path/to/image.jpg')
  .then(image => {
    return image.getBufferAsync(Jimp.MIME_JPEG);
  })
  .then(buffer => {
    console.log('Image buffer:', buffer);
  })
  .catch(err => {
    console.error('Error:', err);
  });

With ‘jimp’, image operations are straightforward, and the package supports various formats and image manipulations.

Advanced Conversions

For advanced scenarios, such as converting an image to a byte array for processing in a database or transmitting over a network, additional encoding or formatting may be required.

Example 6: Base64 Encoding

const fs = require('fs');

let imageBuffer = fs.readFileSync('/path/to/image.jpg');
let imageBase64 = imageBuffer.toString('base64');
console.log(imageBase64);

Converting the buffer to a Base64 string is a common requirement for embedding images in data URIs or for web transmission.

Conclusion

Converting images to byte arrays in Node.js allows for flexible image manipulation and is essential for applications that require image processing or binary data handling. This tutorial covered the basics as well as advanced techniques for working with image data. As always, for production environments, always consider performance, error handling, and security implications when handling file data.

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

Previous Article: Node.js: How to Convert CSV to JSON

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