码迷,mamicode.com
首页 > 其他好文 > 详细

Serverless 实现图片压缩与水印是

时间:2020-06-08 11:02:27      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:_id   前言   图像   图片查看   less   return   展示   图片压缩   需要   

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": {
"url": "http://testpic-1253970026.cos.ap-chengdu.myqcloud.com/testfile",
"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??appid/1253970026:default.printevent.$LATEST",
"reservedInfo": "",
"reqid": 179398952
}
}]
}
根据这个结构,我们可以确定出相关详细信息,例如存储桶/APPID以及图片的Key等。将上面的代码按照函数计算的格式进行改写:

-- coding: utf8 --

import os
from PIL import Image, ImageFont, ImageDraw
from qcloud_cos_v5 import CosConfig
from qcloud_cos_v5 import CosS3Client

secret_id = os.environ.get(‘secret_id‘)
secret_key = os.environ.get(‘secret_key‘)
region = os.environ.get(‘region‘)
cosClient = CosS3Client(CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key))

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

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)

def main_handler(event, context):
for record in event[‘Records‘]:
bucket = record[‘cos‘][‘cosBucket‘][‘name‘] + ‘-‘ + record[‘cos‘][‘cosBucket‘][‘appid‘]
key = "/".join(record[‘cos‘][‘cosObject‘][‘key‘].split("/")[3:])
download_path = ‘/tmp/{}‘.format(key.split(‘/‘)[-1])
download_path = ‘/tmp/{}‘.format(key.split(‘/‘)[-1])
upload_path = ‘/tmp/new_mp4-{}‘.format(key.split(‘/‘)[-1])

重庆代孕【徽信15601836539】、成都代孕【徽信15601836539】、
济南代孕【徽信15601836539】、郑州代孕【徽信15601836539】、
西安代孕【徽信15601836539】、南京代孕【徽信15601836539】、

Serverless 实现图片压缩与水印是

标签:_id   前言   图像   图片查看   less   return   展示   图片压缩   需要   

原文地址:https://www.cnblogs.com/hsoYOI/p/13063976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!