nodejs-如何读取和输出jpg图像?
我一直在寻找如何读取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服务器,该Web服务器响应每个请求显示JPG图像:
var http = require('http')var 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”回调函数启动,并且响应标头具有Content-Type: image/jpeg
。
您甚至可以将image
<img>
与数据URI源一起直接嵌入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>');
以上是 nodejs-如何读取和输出jpg图像? 的全部内容, 来源链接: utcz.com/qa/422955.html