2012-03-02 21 views
28

我一直在試圖找到一個如何閱讀JPEG圖像,然後顯示圖像的例子。nodejs - 如何讀取和輸出jpg圖像?

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數據時出現緩衝區對象。

回答

48

這裏是你如何讀取整個文件內容,如果成功完成,開始它顯示JPG圖像響應每個請求的web服務器:

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

[編輯]你甚至可以使用<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>'); 
+2

有沒有辦法做到這一點,讓我們說我們閱讀jpeg數據,並把它放在src屬性可能通過編碼到base64? – mesh 2012-03-02 22:39:50

+2

太棒了!只是我需要的解決方案。感謝第二個例子。 – mesh 2012-03-03 11:15:41

+0

如果我們有多個圖像呢? – 2017-11-08 21:52:37

-1

兩件事情要記住內容類型和編碼

1.什麼,如果該文件是CSS

如果(/.(css)$ /.test(path)){ res.writeHead(200,{'Content-Type':'text/css'});

res.write(data,'utf8');

} 2如果是什麼文件JPG/PNG

如果(/.(jpg)$/.test(path)){ res.writeHead(200,{'內容類型': 'image/jpg'});

res.end(data,'Base64'); }

上面只是一個示例代碼來解釋答案,而不是確切的代碼模式。