问题
I am trying to get 1*1 pixel as response from my AWS Lambda.
code is like this :
var imgHex = '47494638396101000100800000dbdfef00000021f90401000000002c00000000010001000002024401003b';
var imgBuffer = new Buffer(imgHex, 'hex');
context.succeed({header:"image/png",data:img});
And i mapped response header in API Gateway. But it does't give 1*1 pixel as response.
回答1:
In the Integration Response, replace the default application/json content type with image/png and set the mapping template to:
#set($result = $input.path('$'))
$result.data
Use curl -vvv https://yourendpoint.com/resource to see what headers are returned.
回答2:
Finally got the desired out.
- Instead of converting base64 string to hex, use escaped hexadecimal representation of the 1px*1px image. ie add " \x " to each hexadecimal characters.
- AWS Gateway currently not supporting binary data, so it will add extra characters to data being send. See this. So you may not get desired out for every images.
Here i used image in bmp format. And got 1*1 pixel images as output.
Don't forget to set Content-Type header in integration response.Code:
exports.handler = function(event, context) {
var imageHex = "\x42\x4d\x3c\x00\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00"+
"\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x18\x00\x00\x00"+
"\x00\x00\x06\x00\x00\x00\x27\x00\x00\x00\x27\x00\x00\x00\x00\x00"+
"\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00";
context.succeed({responce:imageHex,header:"image/bmp"});
};
NOTE:
If you are working with new project and you only want to get hit to your lambda function,one more trick is there. You can give any format of images like png,bmp,gif ect as escaped hexadecimal string. The only problem is that aws gateway modifies your string and sometimes you will get this image
.
So Just hide your image by using display:none CSS.
<img style="display:none" src ="http://path_to_your_code">
回答3:
API Gateway does not support binary data at the moment. You will have to base64 encode the image before returning it from Lambda, and decode it on the client side. An example is available here.
Ritisha.
来源:https://stackoverflow.com/questions/38869092/how-to-return-11-pixel-as-response-from-aws-lambda