nodejs - 如何读取和输出 jpg 图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9540978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs - How to read and output jpg image?
提问by mesh
I've been trying to find an example of how to read a jpeg image and then show the image.
我一直在尝试寻找如何读取 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/');
Tried the following code but I think the encoding needs to be set as buffer. Using console.log it outputs 'Object' for the data.
尝试了以下代码,但我认为需要将编码设置为缓冲区。使用 console.log 它输出数据的“对象”。
回答by maerics
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:
以下是读取整个文件内容的方法,如果成功完成,启动一个显示 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/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.
请注意,服务器是由“readFile”回调函数启动的,响应头中有Content-Type: image/jpeg.
[Edit]You could even embed the image in an HTML page directly by using an <img>with a data URI source. For example:
[编辑]您甚至可以通过使用<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>');
回答by user2248133
Two things to keep in mind Content-Typeand the Encoding
需要记住的两件事Content-Type和Encoding
1) What if the file is css
1)如果文件是css怎么办
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
2) 如果文件是 jpg/png 怎么办
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
以上只是解释答案的示例代码,而不是确切的代码模式。

