0

I was wondering how to convert Variable-length binary data(255216255224016747073700110010100255) to a jpeg or png to the web browser?

Example Code:

var Connection = require('tedious').Connection;

    var config = {
        "userName": "user@server.database.windows.net",
        "password": "pswd",
        "server": "server.database.windows.net",
        "options": {
                "database": "db",
                "encrypt": true,
        }
    };

    var connection = new Connection(config);

    connection.on('connect', function(err) {
            console.log("Connected");
        }
    );

var Request = require('tedious').Request;
var result,
    resG;

    function sendResponse() {
        var vals;
            // Convert to string then array
        var resultA = result.toString().split(',');
            // Now I can loop through the data returned
        resultA.forEach(function(val, index, ar) {
            if(vals == null) {
                vals = val;
            } else {
                vals += val;
            }   
        });
        resG.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': vals.length});
        //console.log(vals);
        //resG.end("<img src=\"data:image/jpg;base64," + vals + "\" />");
            // Output data returned from db as string
        resG.end("" + vals);
    }

    function executeStatement() {
         request = new Request("SELECT Photos FROM dbo.tbl WHERE FarmerFirstName='someName' AND FarmerLastName='someLastName'", function(err, rowCount) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(rowCount + ' rows');
                }
            });

            request.on('row', function(columns) {
                columns.forEach(function(column) {
                    result = column.value;
                });
            });

        request.on('doneInProc', function(rowCount, more) {
                    // Got everything needed from db move on to sending a response
            sendResponse();
        });

            connection.execSql(request);
    }

var http = require('http'),
    director = require('director');

var router = new director.http.Router({
    "/": {
        get: executeStatement
    }
});

var server = http.createServer(function (req, res) { 
  // set global res var
  resG = res;
  router.dispatch(req, res, function (err) {
    if (err) {
      res.writeHead(404);
      res.end();
    }
 });
});

server.listen(80);

I'm using tedious for my db connector and director as my router.

camelCaseD
  • 2,483
  • 5
  • 29
  • 44
  • What do mean by convert it to a JPEG? What is the original data? – loganfsmyth Feb 02 '13 at 23:17
  • Convert the data to base64 string and use as a dataUri in the browser. `new Buffer(data).toString('base64')` – RayViljoen Feb 02 '13 at 23:23
  • @loganfsmyth the original data is in the parenthesis but not all of it because its 40,000+ characters. Also I need to convert it to a jpeg because when the header `Content-Type` is set to `image/jpeg` it can't render it correctly. – camelCaseD Feb 03 '13 at 00:18
  • @camelCaseD Sorry, the part that is confusing me is that you say binary data, but your example data is numbers. Is that hex, or base64, or what? If it's a string, what format is that data in? And to confirm, that data already JPEG, right? If not, what does converting an arbitrary binary value into a JPEG even mean? – loganfsmyth Feb 03 '13 at 00:24
  • @loganfsmyth Yes the data is already jpeg. Its [`Variable-length binary data`](http://msdn.microsoft.com/en-us/library/ms187993.aspx) from a mssql db. – camelCaseD Feb 03 '13 at 00:30
  • @camelCaseD That is the type on the database side, but what is the type in Node? Is it a string, a Buffer? If you show some sample code or explain how you got the example value you are printing, it might be easier. What library are you using to connect to the database? – loganfsmyth Feb 03 '13 at 00:36
  • @loganfsmyth I updated my question with the example code – camelCaseD Feb 03 '13 at 00:46
  • Thanks for the example code. Your `toString` and `split` calls obscure the original data, so it was impossible to guess what the initial data was. Do you want to serve this image as an HTML page with a data URL, or do you want to serve an actual image file with `content-type` `image/jpeg`? – loganfsmyth Feb 03 '13 at 01:32

1 Answers1

3

The result is already an array of bytes for the Image. You do not need to do any fancy transformations on it. This should work.

function sendResponse() {
    resG.writeHead(200, {'Content-Type': 'image/jpeg', 'Content-Length': result.length});

    resG.end(new Buffer(result));
}

or if you want to serve it as part of an HTML page, this:

function sendResponse() {
    resG.writeHead(200, {'Content-Type': 'text/html'});

    var vals = (new Buffer(result)).toString('base64')

    resG.end("<html><body>" +
        "<img src=\"data:image/jpg;base64," + vals + "\" />" +
        "</body></html>");
}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251