nodejs write raw image data to jpeg file?

拈花ヽ惹草 提交于 2019-12-03 07:11:49

Here's an example, which downloads http://upload.wikimedia.org/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg to name.jpeg

var fs=require('fs');
var http=require('http');

var f=fs.createWriteStream('name.jpeg');

var options={
    host:'upload.wikimedia.org',
    port:80,
    path:'/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg'
}

http.get(options,function(res){
    res.on('data', function (chunk) {
        f.write(chunk);
    });
    res.on('end',function(){
        f.end();
    });
});

A slightly shorter version, which uses Stream.pipe:

var http = require('http'),
    fs = require('fs'),
    imgSource = 'http://upload.wikimedia.org/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg';

http.get(imgSource, function(res) {
  res.pipe(fs.createWriteStream('wiki.jpg'));
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!