我想知道如何将Variable-length binary data
(255216255224016747073700110010100255
)转换为jpeg或png到Web浏览器?
示例代码:
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);
我使用繁琐的数据库连接器和控制器作为我的路由器。
result
已经是图像的字节数组。您无需对其进行任何花哨的转换。这应该有效。
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'image/jpeg', 'Content-Length': result.length});
resG.end(new Buffer(result));
}
或者,如果您想将其作为 HTML 页面的一部分提供,请执行以下操作:
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>");
}