Skip to content
Advertisement

Node.JS JavaScript buffer to image conversion not a valid bitmap file

I’m trying to transfer an image file data from one node.js script to another.

I read the image file in ‘parameter.js’ using ‘readfilesync’, then transfer it to another script ‘convert.js’.

convert.js is meant to re-convert the file data back to an image using WriteFile – and it seems to do a good job.

However, when I try to open the newly created file, I get the error like;

This is not a valid bitmap file, or its format is not currently supported.

Could you help me spot the problem?

Thanks for your help!

parameter.js:

// Path to image file
let datasetRoute = resolve('./app/scripts/myphotos/bubbles1.png');

// Get image file
let file = readDataset();

// Function to get image file
function readDataset() {

    try { 

        // Fetch dataset using new 'currentPage' number
        return fs.readFileSync(datasetRoute,  'utf8');
    }

    catch (err) { 
        return err;
    }
}

// Create parameter function
const parameterFunctions = {

    // Define function parameters
    
    // Parameter 1
    parameter1: file, // set parameter1 as value of file

}

convert.js:

var bytes = params.uParams[0].parameter1.replace(/^data:image/png;base64,/, "");

fs.writeFileSync('app/scripts/media/test.png', bytes, 'base64', (err) => {
    if (!err) 
    console.log(`Image saved!`);
});

Advertisement

Answer

Converted the entire operation into a simple read and write ‘binary’ format.

Finally worked!

Here’s the code:

parameter.js:


// Path to image file
let datasetRoute = resolve('./app/scripts/myphotos/bubbles1.png');

// Get image file
let file = readDataset();

// Function to get image file
function readDataset() {

    try { 

        // Fetch dataset using new 'currentPage' number
        return fs.readFileSync(datasetRoute, 'binary');
    }

    catch (err) { 
        return err;
    }
}

// Create parameter function
const parameterFunctions = {

    // Define function parameters
    
    // Parameter 1
    parameter1: file, // set parameter1 as value of file

}

convert.js:

var bytes = params.uParams[0].parameter1;

fs.writeFileSync('app/scripts/media/test.png', bytes, 'binary', (err) => {
    if (!err) 
    console.log(`Image saved!`);
});

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement