Image to binary Using NodeJs

Recently I found online a question, asked by some unknown, how to convert an image to binary using NodeJs? Well, it’s related to the file system queries in NodeJs, but he/she might be looking for a way to store the image in the database or something. Anyways let’s continue.

  • To convert images in Node.js, there are several libraries available. One popular library is Sharp, which supports various image file formats such as JPEG, PNG, GIF, WebP, AVIF, SVG, and TIFF.
  • With Sharp, you can read an image and extract its metadata, resize, change an image format, compress an image, crop, grayscale, rotate, and blur an image, composite images, and add text to an image.
  • Another library is ImageMagick, which can be used with Multer to build an image converter app in Node.js and Express.

But still, if you want a solution for reading files (obviously you can read images too) and getting it converted to binary, I wrote a small code in NodeJS, have a look, and I hope it will help you out. It is all about reading a file into binary, but surely you can convert the string to array or byte-array. Please let me know if you get stuck here in the comments below.

Before we start, let me tell you,

const fs = require("fs")

I have included ‘file-system’ dependency because we need to be able to read the file from the file system. The goal is to accept the file from a defined path and read it to convert it into binary.

Oh by the way, ever wondered what happens behind the scenes of smooth web interactions? Anyways back to to topic.

code for converting an image to binary using NodeJs

Let’s create ConvertImageToBinary function to convert an image file into a binary format and save it with a .bin extension. This function is useful for various scenarios, such as when you need to process or transmit images in a binary format.

Function Definition

In this section, we’ll dive into the ConvertImageToBinary function, which is designed to convert an image file into a binary format and save it with a .bin extension. This function is useful for various scenarios, such as when processing or transmitting images in a binary format.

The ConvertImageToBinary function takes three parameters:

  • filePath: The path to the image file you want to convert.
  • destinationPath (optional): The directory where you want to save the binary file.
  • customFileName (optional): A custom name for the binary file. If not provided, the original file name will be used with a .bin extension.

Here’s how the function works:

  1. Read the Image File Synchronously: The function uses fs.readFileSync to read the image file specified by filePath. Reading the file synchronously ensures that the entire file is read into memory before proceeding.

    const data = fs.readFileSync(filePath);

  2. Convert the Image Data to Binary: The read data is converted to a binary string using the toString('binary') method.

    const binaryData = data.toString('binary'); 
    console.log('Binary Data:', binaryData);

  3. Determine the Output File Name and Path: The function constructs the output file name based on the provided customFileName or the original file name with a .bin extension. It then constructs the full output file path using path.join.

    const originalFileName = path.basename(filePath);
    const outputFileName = customFileName ? `${customFileName}.bin` : `${originalFileName}.bin`;
    const outputFilePath = path.join(destinationPath, outputFileName);

  4. Write the Binary Data to the Output File: The binary data is written to the output file using fs.writeFileSync. Writing the file synchronously ensures that the file is fully written before the function completes.

    fs.writeFileSync(outputFilePath, binaryData, 'binary'); 
    console.log('Binary data saved to', outputFilePath);

This function provides a straightforward way to convert images to binary format, making it easier to handle image data in binary form for various applications.

Image To Binary: Complete Function

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

/**
 * @auther: Shankha
 * Converts an image to binary and saves it to a file with a .bin extension.
 * @param {string} filePath - The path to the image file.
 * @param {string} [destinationPath] - The optional path to save the binary file.
 * @param {string} [customFileName] - The optional custom name (without extention) for the binary file.
 */
const ConvertImageToBinary = (filePath, destinationPath = '', customFileName = '') => {
  try {
    const data = fs.readFileSync(filePath);
    const binaryData = data.toString('binary');

    const originalFileName = path.basename(filePath);
    const outputFileName = customFileName ? `${customFileName}.bin` : `${originalFileName}.bin`;
    const outputFilePath = path.join(destinationPath, outputFileName);

    fs.writeFileSync(outputFilePath, binaryData, 'binary');

    const outputFullFilePath = path.resolve(outputFilePath)
    console.log('Binary data saved to', outputFullFilePath);
    return {
      outputFileName,
      destinationPath: outputFullFilePath
    }
  } catch (err) {
    console.error('Error processing the file:', err);
  }
};

// Usage

// Provide the path to your image file
const imagePath = path.join(__dirname, 'your-image.jpg');
 
// With all parameters
ConvertImageToBinary(imagePath, 'path/to/save', 'custom-name');

// With only destination path
ConvertImageToBinary(imagePath, 'path/to/save');

// With default parameters (original file name in the current directory)
ConvertImageToBinary(imagePath);

Converting binary back to image file

Now let’s create another function, ConvertBinaryToImage to convert binary data back into the original image format. This function is essential when you need to restore image files from their binary representations.

Function Definition

ConvertBinaryToImage function takes three parameters:

  • binaryFilePath: The path to the binary file you want to convert back to an image.
  • destinationPath (optional): The directory where you want to save the restored image file.
  • customFileName (optional): A custom name for the restored image file. If not provided, the original file name (without the .bin extension) will be used.

Here’s how the function works:

  1. Read the Binary File Synchronously: The function uses fs.readFileSync to read the binary file specified by binaryFilePath. Reading the file synchronously ensures that the entire file is read into memory before proceeding.

    const data = fs.readFileSync(binaryFilePath, 'binary');

  2. Determine the Output File Name and Path: The function constructs the output file name based on the provided customFileName or the original file name (stripped of the .bin extension). It then constructs the full output file path using path.join.

    const originalFileName = path.basename(binaryFilePath, '.bin'); 
    const outputFileName = customFileName ? customFileName : originalFileName; 
    const originalFilePath = path.join(destinationPath, outputFileName);

  3. Write the Binary Data to the Output File: The binary data is written to the output file using fs.writeFileSync. Writing the file synchronously ensures that the file is fully written before the function completes.

    fs.writeFileSync(originalFilePath, data, 'binary'); 
    console.log('Image file saved as', originalFilePath);

This function provides an efficient way to convert binary data back to its original image format, enabling you to restore images from their binary representations seamlessly.

Binary To Image: Complete Function

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

/**
 * @auther: Shankha
 * Converts binary data back to the original image file.
 * @param {string} binaryFilePath - The path to the binary file with a .<extension>.bin extension 
 *                                  (i.e. image.jpg.bin or img.png.bin)
 * @param {string} [destinationPath] - The optional path to save the restored image file.
 * @param {string} [customFileName] - The optional custom name (without extention) for the restored image file.
 */
const ConvertBinaryToImage = (binaryFilePath, destinationPath, customFileName) => {
  try {
    const data = fs.readFileSync(binaryFilePath, 'binary');

    const originalFileName = path.basename(binaryFilePath, '.bin');
    const extension = path.extname(originalFileName);
    const outputFileName = customFileName ? customFileName + extension : originalFileName;
    const originalFilePath = path.join(destinationPath, outputFileName);

    fs.writeFileSync(originalFilePath, data, 'binary');
    console.log('Image file saved as', originalFilePath);
    return {
      outputFileName,
      destinationPath: path.resolve(originalFilePath)
    }
  } catch (err) {
    console.error('Error processing the binary file:', err);
  }
};



// Usage

// Provide the path to your image file
const imagePath = path.join(__dirname, 'your-image.jpg.bin');

// Convert binary back to image with destination path and custom file name
ConvertBinaryToImage(binaryFilePath, 'path/to/save', 'custom-restored-name');

// Convert binary back to image with destination path
ConvertBinaryToImage(binaryFilePath, 'path/to/save');

// Convert binary back to image with default path (current directory)
ConvertBinaryToImage(binaryFilePath);

I guess this code is self-documented enough and you don’t need me to explain. But still, if you face any issues or face any error please let me know in the comment section below. I’ll try my best to solve your problem.

Also, if you are interested in software solutions, you must be interested in Enterprise Solution Architecture, here you will find in-depth insights.

Awesome, you did it.

Extras

The next section is optional, if you are looking for class based approach.

Let’s create a Image Conversion Class [Complete Code]

Let convert the above functionality in the compact JS class for the ease of use.

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

class ImageConverter {
  /**
   * @auther: Shankha
   * Converts an image to binary and saves it to a file with a .bin extension.
   * @param {string} filePath - The path to the image file.
   * @param {string} [destinationPath] - The optional path to save the binary file.
   * @param {string} [customFileName] - The optional custom name for the binary file.
   */
  static ConvertImageToBinary(filePath, destinationPath, customFileName) {
    try {
      const data = fs.readFileSync(filePath);
      const binaryData = data.toString('binary');

      const originalFileName = path.basename(filePath);
      const outputFileName = customFileName ? `${customFileName}.bin` : `${originalFileName}.bin`;
      const outputFilePath = path.join(destinationPath, outputFileName);

      fs.writeFileSync(outputFilePath, binaryData, 'binary');
      console.log('Binary data saved to', outputFilePath);
    } catch (err) {
      console.error('Error converting image to binary:', err);
    }
  }

  /**
   * @auther: Shankha
   * Converts binary data back to the original image file.
   * @param {string} binaryFilePath - The path to the binary file with a .bin extension.
   * @param {string} [destinationPath] - The optional path to save the restored image file.
   * @param {string} [customFileName] - The optional custom name for the restored image file.
   */
  static ConvertBinaryToImage(binaryFilePath, destinationPath, customFileName) {
    try {
      const data = fs.readFileSync(binaryFilePath, 'binary');

      const originalFileName = path.basename(binaryFilePath, '.bin');
      const outputFileName = customFileName ? customFileName : originalFileName;
      const originalFilePath = path.join(destinationPath, outputFileName);

      fs.writeFileSync(originalFilePath, data, 'binary');
      console.log('Image file saved as', originalFilePath);
    } catch (err) {
      console.error('Error converting binary to image:', err);
    }
  }
}

// Provide the path to your image file
const imagePath = path.join(__dirname, 'your-image.jpg');

// Call the static method to convert the image to binary
ImageConverter.ConvertImageToBinary(imagePath);

// Path to the binary file
const binaryFilePath = `${imagePath}.bin`;

// Call the static method to convert binary back to image
ImageConverter.ConvertBinaryToImage(binaryFilePath);
If you are using TypeScript [Complete Code]
import * as fs from 'fs';
import * as path from 'path';

class ImageConverter {
  /**
   * @auther: Shankha
   * Converts an image to binary and saves it to a file with a .bin extension.
   * @param {string} filePath - The path to the image file.
   * @param {string} [destinationPath] - The optional path to save the binary file.
   * @param {string} [customFileName] - The optional custom name for the binary file.
   */
  static ConvertImageToBinary(filePath: string, destinationPath?: string, customFileName?: string): void {
    try {
      const data: Buffer = fs.readFileSync(filePath);
      const binaryData: string = data.toString('binary');

      const originalFileName: string = path.basename(filePath);
      const outputFileName: string = customFileName ? `${customFileName}.bin` : `${originalFileName}.bin`;
      const outputFilePath: string = path.join(destinationPath, outputFileName);

      fs.writeFileSync(outputFilePath, binaryData, 'binary');
      console.log('Binary data saved to', outputFilePath);
    } catch (err) {
      console.error('Error converting image to binary:', err);
    }
  }

  /**
   * @auther: Shankha
   * Converts binary data back to the original image file.
   * @param {string} binaryFilePath - The path to the binary file with a .bin extension.
   * @param {string} [destinationPath] - The optional path to save the restored image file.
   * @param {string} [customFileName] - The optional custom name for the restored image file.
   */
  static ConvertBinaryToImage(binaryFilePath: string, destinationPath?: string, customFileName?: string): void {
    try {
      const data: string = fs.readFileSync(binaryFilePath, 'binary');

      const originalFileName: string = path.basename(binaryFilePath, '.bin');
      const outputFileName: string = customFileName ? customFileName : originalFileName;
      const originalFilePath: string = path.join(destinationPath, outputFileName);

      fs.writeFileSync(originalFilePath, data, 'binary');
      console.log('Image file saved as', originalFilePath);
    } catch (err) {
      console.error('Error converting binary to image:', err);
    }
  }
}

// Provide the path to your image file
const imagePath: string = path.join(__dirname, 'your-image.jpg');

// Call the static method to convert the image to binary
ImageConverter.ConvertImageToBinary(imagePath);

// Path to the binary file
const binaryFilePath: string = `${imagePath}.bin`;

// Call the static method to convert binary back to image
ImageConverter.ConvertBinaryToImage(binaryFilePath);

Conclusion

The “image to binary using NodeJs” solution stands as my proposed solution to the problem at hand. It leverages the power of JavaScript and a vibrant ecosystem of libraries to provide a flexible and efficient approach. Remember, the choice should be made after considering factors like image format, conversion goals, performance requirements, and security concerns.

But by presenting this solution and inviting collaboration, I hope to spark dialogue and refine our collective understanding. Let’s share our experiences and insights in the comments, and together, we can ensure this approach delivers optimal outcomes for diverse use cases.

Similar Posts

2 Comments

    1. Hi Klaus,

      Thankyou so much for taking the time to comment! I really appreciate your input. To answer your question, I’ve jotted down a few points:

        1. Converting an image to binary is essential when you need to serialize data for storage – whether it’s for simple file storage or a database.
        2. By turning it into a binary string, you make it harmless, effectively neutralizing any malicious content just by storing it as a binary string.
        3. Some people use hex for serialization, but it significantly increases file size compared to binary.

      hex vs binary file size

      And yes, you are right, if you change the extension from .bin to .jpg it will open like the original jpg file.

Leave a Reply

Your email address will not be published. Required fields are marked *