nodejs – 如何读取和输出jpg图像?

我一直在试图find一个如何读取JPEG图像,然后显示图像的例子。

var http = require('http'), fs = require('fs'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); fs.readFile('image.jpg', function (err, data) { if (err) throw err; res.write(data); }); res.end(); }).listen(8124, "127.0.0.1"); console.log('Server running at http://127.0.0.1:8124/'); 

试了下面的代码,但我认为编码需要设置为当我console.log数据缓冲区对象出现。

这里是如何读取整个文件内容,如果成功完成,启动一个Web服务器,显示JPG图像以响应每个请求:

 var http = require('http') , fs = require('fs'); fs.readFile('image.jpg', function(err, data) { if (err) throw err; // Fail if the file can't be read. http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'image/jpeg'}); res.end(data); // Send the file data to the browser. }).listen(8124); console.log('Server running at http://localhost:8124/'); }); 

请注意,服务器是通过“readFile”callback函数启动的,并且响应标头具有Content-Type: image/jpeg

[编辑]您甚至可以直接使用带有数据URI源的<img>将图像embedded到HTML页面中。 例如:

  res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<html><body><img src="data:image/jpeg;base64,') res.write(Buffer.from(data).toString('base64')); res.end('"/></body></html>');