本文介绍了nodejs - 如何读取和输出jpg图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I've been trying to find an example of how to read a jpeg image and then show the image.

我一直在试图找到一个如何读取jpeg图像然后显示图像的例子。 http = require('http'),fs = require('fs');
$ b $ 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/');

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/');

尝试了下面的代码,但我认为编码需要设置为当我控制台时显示缓冲区对象。记录数据。

Tried the following code but I think the encoding needs to be set as buffer object appears when I console.log the data.

推荐答案

这里是如何读取整个文件的内容,如果成功的话,启动一个webserver来显示这个JPG图片响应每个请求:
$ b

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

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回调函数启动的,响应头是 Content-Type:image / jpeg

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

一个HTML页面直接通过使用< img> 与。例如:
$ b

You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  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图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 17:12