如何返回1 * 1像素作为AWS Lambda的响应? [英] How to return 1*1 pixel as response from AWS Lambda?

查看:97
本文介绍了如何返回1 * 1像素作为AWS Lambda的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的 AWS Lambda 获得1 * 1像素作为响应.

I am trying to get 1*1 pixel as response from my AWS Lambda.

代码是这样的:

var imgHex = '47494638396101000100800000dbdfef00000021f90401000000002c00000000010001000002024401003b';
var imgBuffer = new Buffer(imgHex, 'hex');
context.succeed({header:"image/png",data:img}); 

我在 API网关中映射了响应头. 但是它没有给出1 * 1像素作为响应.

And i mapped response header in API Gateway. But it does't give 1*1 pixel as response.

推荐答案

最后得到了期望的结果.

Finally got the desired out.

  • 使用转义的十六进制代替将base64字符串转换为十六进制 1px * 1px 图片的表示形式.即在每个十六进制字符后添加" \ x ".
  • AWS Gateway当前不支持二进制数据,因此它将添加 要发送的数据中包含多余的字符.参见.因此,您可能不会对每张图像都感到满意.
  • 这里我使用的是 bmp 格式的图片.并得到1 * 1像素的图像作为 输出.
    不要忘记在集成响应中设置 Content-Type 标头.

  • 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.

代码:

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"});
};

注意:
如果您正在使用新项目,并且只想使用lambda函数,那么还有另外一个技巧.您可以使用png,bmp,gif等任意格式的图像作为转义的十六进制字符串.唯一的问题是,aws网关会修改您的字符串,有时您会得到此图像
.
因此,只需使用 display:none CSS隐藏您的图像即可.

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">

这篇关于如何返回1 * 1像素作为AWS Lambda的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆