1
votes

I have a node js project which requires to reduce the size of images before sending to the client. I am using request library and sharp library.

The source of the images is a signed aws s3 bucket url - e.g

{http://my_intentionally_hidden_url/api/getImage?image=https://my_intentionally_hidden_bucket_name_and_path.s3.eu-central-1.amazonaws.com/name_it/q_i_9.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=My_intentionally_hidden_credentials%2F20190813%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20190813T221026Z&X-Amz-Expires=120&X-Amz-Signature=1c81c2b69d82e116d8ea398604b44dfb3ca2bb7d9b961d639766630fe4b4eb95&X-Amz-SignedHeaders=host&width=1440&height=120}

I am using the following block of code to get the aboove url from s3, resize it and then send the resized image back to the client

module.exports.getImage = (req,res) => {
  const url = req.query.image; //the signed url
  var width = parseInt(req.query.width);
  var height = parseInt(req.query.height);

  if(width > 300){
      width = 300;
  }

  if(height > 300){
      height = 300;
  }

  request({url, encoding: null }, (error, response, body ) => {
      console.log({body});
      console.log({error});


      if(!error) {
         sharp(body)
            .resize (width,height)
            .webp({ lossless: false })
            .toBuffer()
            .then(data => {
                console.log("we we we")
                return res.send(data);
                console.log({data});
            })
            .catch(err => {
                console.log({err})
            })

      }
      else{
          console.log({error})
      }
   })
}

In the above call,

The url was signed a couple of minutes ago to make it public, and the result of the console.log({body}) is binary data, which is what should be returned,

The first console.log({error}) is null.

The problem is where the console.log({err}) is and it shows -

{ err: Error: Input buffer contains unsupported image format }

I have another bucket on s3 and if i take the url of a public image (url that is not signed) on that bucket and do -

 ....
 const url = "https://My_hidden_bucket_name.s3-eu-west-1.amazonaws.com/o_d_3.jpg"
 var width = parseInt(req.query.width);
 var height = parseInt(req.query.height);
 ....

I am sure that the signed urls's are working because the signed url's have been tested when they are called from the client and the image shows.

I have tried using sharp without the .webp() and testing it out and i get the same result, i have used it with the other formats that sharp offers - jpeg, png and the same error message comes up. It appears request is returning the right response.

1

1 Answers