其他分享
首页 > 其他分享> > Serverless 实现图片压缩与水印是他的第八季

Serverless 实现图片压缩与水印是他的第八季

作者:互联网

个image对象和宽度传入,通过resize方法进行大小的调整,实现压缩功能。

def compressImage(image, width):
height = image.size[1] / (image.size[0] / width)
return image.resize((int(width), int(height)))
图像水印

图像水印部分采用的是文字水印,除了文字水印还可以考虑使用图片水印等。

此处为了将水印放在图像的右下角,并且恰好不超出图像范围,进行了每个字符大小的获取:

height = []
width = []
for eveStr in watermarkStr:
thisWidth, thisHeight = drawImage.textsize(eveStr, font)
height.append(thisHeight)
width.append(thisWidth)
通过这样处理之后,得到的height列表就是所有即将水印文字的高度,width列表是所有即将水印文字的宽度。此处要将水印放在右下角只需要在图片整体高度上减去height列表最大值,图片整体宽度基础上减去width列表的总和即可:

def watermarImage(image, watermarkStr):
txtImage = Image.new('RGBA', image.size, (0, 0, 0, 0))
font = ImageFont.truetype("Brimborion.TTF", 40)
drawImage = ImageDraw.Draw(txtImage)
height = []
width = []
for eveStr in watermarkStr:
thisWidth, thisHeight = drawImage.textsize(eveStr, font)
height.append(thisHeight)
width.append(thisWidth)
drawImage.text((txtImage.size[0] - sum(width) - 10, txtImage.size[1] - max(height) - 10),
watermarkStr, font=font,
fill=(255, 255, 255, 255))
return Image.alpha_composite(image, txtImage)
部署到云函数

通过函数的事件描述,可以确定腾讯云函数的对象存储触发器事件结果为:

{
"Records": [
{
"cos": {
"cosSchemaVersion": "1.0",
"cosObject": {,
"meta": {
"x-cos-request-id": "NWMxOWY4MGFfMjViMjU4NjRfMTUyMV8yNzhhZjM=",
"Content-Type": ""
},
"vid": "",
"key": "/1253970026/testpic/testfile",
"size": 1029
},
"cosBucket": {
"region": "cd",
"name": "testpic",
"appid": "1253970026"
},
"cosNotificationId": "unkown"
},
"event": {
"eventName": "cos: ObjectCreated:Post",
"eventVersion": "1.0",
"eventTime": 1545205770,
"eventSource": "qcs::cos",
"requestParameters": {
"requestSourceIP": "192.168.15.101",
"requestHeaders": {
"Authorization": "q-sign-algorithm=sha1&q-ak=AKIDQm6iUh2NJ6jL41tVUis9KpY5Rgv49zyC&q-sign-time=1545205709;1545215769&q-key-time=1545205709;1545215769&q-header-list=host;x-cos-storage-class&q-url-param-list=&q-signature=098ac7dfe9cf21116f946c4b4c29001c2b449b14"
}
},
"eventQueue": "qcs:0:lambda

标签:Serverless,www,庭院,第八,水印,wenjuan,https,com,齐侯
来源: https://www.cnblogs.com/hsoYOI/p/13084140.html