【问题标题】:nodejs - How to read and output jpg image?nodejs - 如何读取和输出 jpg 图像?
【发布时间】:2020-03-26 23:27:33
【问题描述】:

我一直在尝试寻找如何读取 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 它为数据输出“对象”。

【问题讨论】:

    标签: node.js filesystems


    【解决方案1】:

    以下是读取整个文件内容的方法,如果成功完成,启动一个显示 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

    [编辑]您甚至可以通过使用<img>data URI source 将图像直接嵌入到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>');
    

    【讨论】:

    • 有没有办法做到这一点,假设我们读取 jpeg 数据并放入 src 属性,可能通过将其编码为 base64?
    • 太棒了!正是我需要的解决方案。谢谢你的第二个例子。
    • 如果我们有多个图像怎么办?
    【解决方案2】:

    要记住两件事 Content-Type编码

    1) 如果文件是css怎么办

    if (/.(css)$/.test(path)) {
      res.writeHead(200, {'Content-Type': 'text/css'}); 
      res.write(data, 'utf8');
    } 
    

    2) 如果文件是jpg/png怎么办

    if (/.(jpg)$/.test(path)) {
      res.writeHead(200, {'Content-Type': 'image/jpg'});
      res.end(data,'Base64');
    }
    

    以上只是解释答案的示例代码,而不是确切的代码模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2023-03-08
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 2015-07-02
      相关资源
      最近更新 更多