How to convert image to binary NodeJS?

Recently I found online a question, asked by some unknown, how to convert image to byte array NodeJS? Well it’s quite 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 (if so I give you way more efficient solution, read it here).

Which data type is used to store pictures and how?

But still, if you want a solution for reading files(obviously you can read images too) and get it converted to binary, I wrote a small code in NodeJS, have a look 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. If you get suck here, please let me know in the comments below.

Before we start, let me tell you,

let 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 here is to accept the file from a defined path and read it to convert it into binary.

Solution

const getBinary = async (params = undefined) => {
    /**
     * @auther: Shankha
     * @date: 26 Apr, 2020
     */

    // params format:
    // getBinary({
    //   path : '<file_relative_path>',
    //   padlength: '<prepending_padding_length>', (Default: 4)
    //   debug: false,                             (Default: true)
    //   limit: 10                                 (Default: Full_File_Length)
    //   putSpacing: Boolean                       (Default: false)
    // })

    // Params Description:
    //   1. path: Specifies the relative file path, to be read.
    //   2. padlength: After reading the file, it reads object as number 
    //                 (ex: hex(f): 1111, hex(0): 0), so if you need a 
    //                 unform lenght binary string then you will need to 
    //                 fill the strings. as hex(0): 0000 when padlength is 4.
    //   3. limit: limits the read buffer to render.
    //   4. putSpacing: if true it puts a space after each padlength.

    //
    // or
    // getBinary('<file_relative_path>');

    let fs = require("fs");
    let result = '';
    try {

        if ((typeof params) == 'string') {
            params = {
                path: params
            };
        }
        if (params) {
            let mendatoryKeys = ['path'];
            for (let i = 0; i < mendatoryKeys.length; i++) {
                if (!params.hasOwnProperty(mendatoryKeys[i])) {
                    throw "JSON key " + mendatoryKeys[i] + " is expected in prarameter object";
                }
            }
            let hexBuffer = Buffer.from(fs.readFileSync(params.path)).toString('hex');
            let padding = params.hasOwnProperty('padlength') ? params.padlength : 4;
            let limit = params.hasOwnProperty('limit') ? parseInt(params.limit) : hexBuffer.length;
            let putSpacing = params.hasOwnProperty('putSpacing') ? params.putSpacing : false;
            if (typeof putSpacing == 'boolean') {
                putSpacing = putSpacing ? ' ' : '';
            } else {
                throw "JSON key 'putSpacing' is expected as boolean";
            }
            for (let i = 0; i < limit; i++) {
                result += String(parseInt(hexBuffer[i], 16).toString(2).substr(-8)).padStart(padding, '0') + putSpacing;
            }
        } else {
            throw "JSON object is expected as prarameter, but got undefined"
        }
    } catch (e) {
        if (params.hasOwnProperty('debug') ? params.debug : true) {
            console.log(e);
        }
    } finally {
        return (result.trim() === '') ? undefined : result.trim();
    }
}


const main = () => {

    let obj = {
        path: './a.jpg',
        padlength: 4,
        limit: 10
    }
    getBinary(obj).then((data) => {
        console.log(data);
    })

    // or for quick use
    // 
    // getBinary('./a.jpg').then((data)=>{
    //   console.log(data);
    // })
}

main();

 

Okay, that is it. But if you also want a cleanup performed on the system, I mean if you want to delete to a temporary file (say if you did want to upload a file and read it to binary) the add fs.unlink(params.path); just before line 57. It will delete the temporary file after reading.

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

Leave a Reply