Node.js How to convert to image from varbinary of

2019-04-15 23:28发布

问题:

I am accessing third party database where there are images stored in varbinary column. I am writing node.js application to restore varbinary images stored in MS Sql server into .jpg file.

When I query varbinary is returned as buffer but from buffer I am not able to restore image into .jpg file.

For MS Sql server access i am using https://www.npmjs.com/package/mssql libray.

[UPDATE:]: Below are the some of the ways I tried to convert and save as Image.

var decodedImage = new Buffer(varbinaryBufferReturedFromDatabase, 'base64');
var decodedImage = new Buffer(varbinaryBufferReturedFromDatabase, 'hex');
var decodedImage = new Buffer(varbinaryBufferReturedFromDatabase, 'uft8');
var decodedImage = varbinaryBufferReturedFromDatabase.toString('hex');
var decodedImage = varbinaryBufferReturedFromDatabase.toString('base64');
var decodedImage = varbinaryBufferReturedFromDatabase.toString('uft8');

fs.writeFile(__dirname+'/../public/images/img3.jpg', decodedImage, function(err, data){
            if (err) throw err;
        console.log('It\'s saved!');
            cb(data);
    });

回答1:

Resolved It was difficult until I studied how Encoding/Decoding and varbinary works.

Solution : Images were stored as hexadecimal numbers representation of base64 encoded string in Sql server as data type varbinary. While fetching record node.js mssql library converts the hexadecimal numbers into javascript buffer(This buffer is of base64 encoded string and not actual image). Then I converted this buffer back to base64 encoded string of image like..

var originalBase64ImageStr = new Buffer(resultSet[0].Image).toString('utf8');

Then created converted back to actual image buffer like..

var decodedImage = new Buffer(originalBase64ImageStr , 'base64')

fs.writeFile(__dirname+'/../public/images/img3.jpg', decodedImage, function(err, data){
            if (err) throw err;
        console.log('It\'s saved!');
            cb(data);
    });

Note: Node.js mssql library works differently for string representation of varbinary(returned buffer is representation of original string so no need to follow above steps) and image/doc representation of varbinary(returned buffer is representation of base64 encoded string and need to follow above steps).