javascript nodejs 将原始图像数据写入 jpeg 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9168182/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:49:02  来源:igfitidea点击:

nodejs write raw image data to jpeg file?

javascriptnode.jsbufferfs

提问by zumzum

I am getting data from a get request. The data (in the body of the response) looks something like this:

我正在从 get 请求中获取数据。数据(在响应正文中)如下所示:

... ?à???"????????????????????N??!1"AQa2q?#BR±e3brS2á??á$?CDTst¢3&45d?ò?????????????????-??????!1A"Qa?eq±á?2á?ú??????." """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """R1o#a¥7Jí??M6?N? ]·!]=Fv-?`7~q?ee2%·JokkZüCbìt<ù{?9?ù??′(%A,Ià?2I?t×bn6w?ù¥V?2Sà><k5où?92Eh??ü¨/aY!?|?t¥??T}U?|òúμ?xu?f?3 K??{ù{e$·DúBMZ?cp}′R|M?2ó8üg)·ù?f?$zXiRTü}ó?>,êú?íR5y:\ .....

the response headers look like this:

响应标头如下所示:

HTTP/1.1 200 OK
Content-Length: 26965
Access-Control-Allow-Origin: *
Content-Type: image/jpeg; charset=UTF-8
Date: Mon, 06 Feb 2012 21:14:21 GMT
Expires: Mon, 06 Feb 2012 22:14:21 GMT
Cache-Control: public, max-age=3600
Last-Modified: Fri, 13 Feb 2009 23:31:30 GMT
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Server: Dropta Server 1.0
X-Frame-Options: SAMEORIGIN
Connection: close

I want to get the body content which is my image data and save it to a name.jpegfile on the server.

我想获取作为我的图像数据的正文内容并将其保存到name.jpeg服务器上的文件中。

How can I do that? I tried using buffers combined with the fsmodule, but I am kind of lost.

我怎样才能做到这一点?我尝试将缓冲区与fs模块结合使用,但我有点迷茫。

Thanks

谢谢

回答by stewe

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

这是一个示例,它将http://upload.wikimedia.org/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg下载到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();
    });
});

回答by Laurent Perrin

A slightly shorter version, which uses Stream.pipe:

一个稍短的版本,它使用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'));
});