简体   繁体   中英

How to get original image from http response using node.js

I am consuming third party service for downloading images but body of it's response includes html plus base64(not sure) image content on top. Response has content type as image/jpeg; charset=utf-8 image/jpeg; charset=utf-8

Example response:

����JFIF``��C       

 $.' ",#(7),01444'9=82<.342��C          

2!!22222222222222222222222222222222222222222222222222��"��  
���}!1AQa"q2���#B��R��$3br� 
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������    
���w!1AQaq"2�B����  #3R�br�

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body onload="initslide('method1,method2,method3', '');">
    // More html goes here
</body>
</html>

And service call:

var params = {
  url : serviceUrl,
  form : form,
  headers : headers
};

request.post(params, function(error, response, body) {
  if (error) {
    console.error("Error:", error);
    return;
  }
  callback(body); // In body i am getting above response 
});

Now, I am only interested in downloading image portion of it and save it on cloud as png/jpeg format. Any idea how to achieve this in node.js.

I think we can make the assumption that the image won't contain the sequence \\n\\n<! so let's split on that.

var parts = body.split('\n\n<!')

Now the first part should contain our image

var imageData = new Buffer(parts[0], 'binary');

So then we can save this to a file

//I'm just assuming jpg for now
fs.writeFile('out.jpg', imageData, cb);

More can be done to interpret the file type and make it more robust but this is the basic idea behind it.

Alternatively you can read the entire file into a buffer and look for the end of image sequence in the JPEG ( FFD9 ) which will tell you when the image begins and the html ends.

var data = new Buffer(body, 'binary');
for(var i=0; i<data.length; i++){
    if(data[i] === 0xff && data[i+1] === 0xd9){
        //end of file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM