2012-03-02 7 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画像を表示するウェブサーバを起動し、ファイル全体の内容を読み取ることができる方法で、成功した場合:サーバは "によって起動されていることを

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です。

[編集]data URI source<img>を使用して直接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

+2

恐ろしい!ちょうど私が必要とした解決策。その2番目の例をありがとう。 – mesh

+0

複数の画像がある場合はどうなりますか? –

-1

2つのことを念頭のContent-Typeておくとエンコーディングに

ファイルがあれば、CSS

であれば(/.(css)$ 1.What /.test(path))) { res.writeHead(200、{'コンテンツタイプ': 'text/css'});

res.write(data、 'utf8');

} 2ファイルは、JPG/PNG

どのような場合であれば(/.(jpg)$/.test(path)){ res.writeHead(200、{'のContent-Type': 'image/jpg'});

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

上記は、正確なコードパターンではなく、解答を説明するためのサンプルコードです。

関連する問題