Skip to content

Instantly share code, notes, and snippets.

@infinitylogesh
Last active October 10, 2018 01:07
Show Gist options
  • Save infinitylogesh/4e0f774f5f48252a767a65f75e527ccd to your computer and use it in GitHub Desktop.
Save infinitylogesh/4e0f774f5f48252a767a65f75e527ccd to your computer and use it in GitHub Desktop.
Building an AWS lambda service to return binary data (image) as a response without Access header.
let sh = require("sharp")
var ApiBuilder = require('claudia-api-builder'),
api = module.exports = new ApiBuilder();
var req = require('request').defaults({ encoding: null });
module.exports = api;
/*
Router to resize the image
Parameters :
1. url = url of the image
2. w = width
3. h = height
*/
api.get('/resize', function (request) {
let image_url = request.queryString.url;
let width = parseInt(request.queryString.w);
let height = parseInt(request.queryString.h);
const options = {
url: image_url,
method: 'GET'
}
return new Promise(function(resolve,reject){
req(options,async function (err, res, body) {
try{
resolve(await resize_image(body,width,height));
}catch(err){
reject(err);
}
reject(err);
});
});
},{ success: { contentType: 'image/png', contentHandling: 'CONVERT_TO_BINARY'},"isBase64Encoded": true});
/* Helper functions */
// resizes the image to target width and target height and returns a Promise of image buffer.
async function resize_image(image,targetWidth,targetHeight){
return new Promise(async (resolve,reject)=>{
let image_sh = sh(image);
image_sh.resize(targetWidth, targetHeight,{
kernel: sh.kernel.nearest
})
.embed()
.png()
.toBuffer()
.then(data=>resolve(data.toString("base64")))
.catch(err=>reject(err));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment