3

我正在尝试在 node.js 中加载图像文件。该文件将在 ram 中并在主循环之外加载。它只是一个 1x1 像素。

如何打开图像文件?

我尝试了以下方法:

var fs = require('fs');
fs.readFile('/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/pixel1x1.gif', function(err,pixel){
  if(err) {
    console.error("Could not open file: %s", err);
    process.exit(1);
  }
  console.log(pixel);
});


Server running at http://127.0.0.1:8124/
<Buffer 47 49 46 38 39 61 01 00 01 00 80 00 00 00 00 00 ff ff ff 21 f9 04 01 00 00 00 00 2c 00 00 00 00 01 00 01 00 00 02 01 44 00 3b>

图像无法显示,因为它包含错误。

 res.writeHead(200, {'Content-Type': 'image/gif'});
 res.end(pixel);
4

1 回答 1

2

如果它只是一个 1x1 gif 图像,那么你不需要存储图像文件并加载它,因为有一个很好的 NPM 包 blankgif 已经在代码中加载了带有 base64 字符串的空白 1x1 gif,所以它会工作得更快然后单独加载图像。此外,还有一些辅助函数可以帮助您在 expressjs 中发送此图像。

要使用这个包,你可以使用这个代码:

var blankgif = require('blankgif');
var express = require('express');
var app = express();

app.get('/track.gif', blankgif.sendBlankGif);

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

我还假设您要实现此功能,因为您需要使用此空白图像在某处跟踪访问者。所以你可以用这个库以两种方式做到这一点:

1)使用blankgif的特殊中间件,为您的响应对象添加附加功能

var blankgif = require('blankgif');
var express = require('express');
var app = express();

app.use(blankgif.middleware());

app.get('/track.gif', function(req, res) {
  console.log('request information logged');

  res.set('Cache-Control', 'public, max-age=0');
  res.status(200).sendBlankGif();
});

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

2) 只需在 blankgif.sendBlankGif 之前使用自定义中间件

var blankgif = require('blankgif');
var express = require('express');
var app = express();

app.get('/track.gif', function(req, res, next) {
  console.log('request information logged');
  next();
}, blankgif.sendBlankGif);

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

此外,如果您出于某些原因不想使用此库(或者如果您想要另一个 gif 图像),您可以手动提供此图像:

var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');

var buff = null;

fs.readFile(path.resolve(__dirname, 'pixel1x1.gif'), function (err, pixel) {
  if (err) {
    console.error("Could not open file: %s", err);
    process.exit(1);
  }

  buff = pixel;
});

app.get('/track.gif', function (req, res) {
  console.log('request information logged');

  res.type('image/gif');
  res.send(buff);
});

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});
于 2016-04-20T00:52:51.437 回答