node.jsimageblobnode.js-fs

Convert BLOB of a image to a image file in nodejs


I am working on a api that fetches the image from the server and it is giving the image as blob and now i wanted to convert that blob to a image file and save locally

I had tried to convert the image to base64 and then convert it to image and also tried some stackoverflow fixes but none of them worked

Here is the code

async function query(data) {
  var url;
  url = "https://api-inference.huggingface.co/models/prompthero/openjourney";

  try {
    const response = await request(
      {
        method: 'POST',
        uri: url,
        headers: {
          'Authorization': 'AUTHTOKEN-HERE!!!',
        },
        body: JSON.stringify(data),
      }
    );
    const result = await response.blob();
    console.log(result)
    return result;
  }
  catch (err) {
    console.log("error occured");
    console.log(err)
  }

}

Solution

  • Here is how we can download the image file.

    import fs from 'fs';
    
    async function query(data) {
      var url;
      url = "https://api-inference.huggingface.co/models/prompthero/openjourney";
    
      const response = await fetch(
            url,
            {
                headers: { Authorization: "TOKEN HERE !!!" },
                method: "POST",
                body: JSON.stringify(data),
            }
        );
        const result = await response.blob();
        return result;
    }
    
    query({"inputs": "Astronaut riding a horse"}).then(async (response) => {
      fs.writeFileSync('downloaded_image.jpg', Buffer.from(await response.arrayBuffer()));
      console.log('Image downloaded successfully.');
    });
    

    You can add up the error handling logics but this above logic will download the image.