时间:2023-07-03 16:45:02 | 来源:网站运营
时间:2023-07-03 16:45:02 来源:网站运营
「实践」如何优雅地给网站图片加水印:很多论坛、博客在进行图片上传之后,都会给自己的图像加上水印,这样可以证明这张图片「属于我」或者是「来自我的博客/网站」。那么使用 Serverless 技术来加水印的方法比传统方法好在哪儿呢,本文将对此进行一个简单的分享。传统的加水印的方法,通常是在流程内进行。即:
{ "Records":[ { "event": { "eventVersion":"1.0", "eventSource":"qcs::cos", "eventName":"cos: ObjectCreated: *", "eventTime":1501054710, "eventQueue":"qcs:0:cos:gz:1251111111:cos", "requestParameters":{ "requestSourceIP": "111.111.111.111", "requestHeaders":{ "Authorization": "上传的鉴权信息" } } }, "cos":{ "cosSchemaVersion":"1.0", "cosNotificationId":"设置的或返回的 ID", "cosBucket":{ "name":"bucketname", "appid":"appId", "region":"gz" }, "cosObject":{ "key":"/appid/bucketname/DSC_0002.JPG", "size":2598526, "meta":{ "Content-Type": "text/plain", "x-cos-meta-test": "自定义的 meta", "x-image-test": "自定义的 meta" }, "url": "访问文件的源站url" } } } ]}
这里面可以看到整个一个数据结构,需要注意 Records 是一个数组格式,其次就是:{ "Records":[ { "event": { "eventVersion":"1.0", "eventSource":"qcs::cos", "eventName":"cos: ObjectCreated: *", "eventTime":1501054710, "eventQueue":"qcs:0:cos:gz:1251111111:cos", "requestParameters":{ "requestSourceIP": "111.111.111.111", "requestHeaders":{ "Authorization": "上传的鉴权信息" } } }, "cos":{ "cosSchemaVersion":"1.0", "cosNotificationId":"设置的或返回的 ID", "cosBucket":{ "name":"mytestcos", "appid":"appId", "region":"gz" }, "cosObject":{ "key":"test.png", "size":2598526, "meta":{ "Content-Type": "text/plain", "x-cos-meta-test": "自定义的 meta", "x-image-test": "自定义的 meta" }, "url": "访问文件的源站url" } } } ]}
这里主要修改了我的 cosBucket-name:mytestcos,以及 key:test.pngdef add_word(pic_path, save_path): # 打开图片 im = Image.open(pic_path).convert('RGBA') # 新建一个空白图片,尺寸与打开图片一样 txt = Image.new('RGBA', im.size, (0, 0, 0, 0)) # 设置字体 fnt = ImageFont.truetype("/tmp/font.ttf", 40) # 操作新建的空白图片>>将新建的图片添入画板 d = ImageDraw.Draw(txt) # 在新建的图片上添加字体 d.text((txt.size[0] - 220, txt.size[1] - 80), "By Dfounder", font=fnt, fill=(255, 255, 255, 255)) # 合并两个图片 out = Image.alpha_composite(im, txt) # 保存图像 out.save(save_path)
在添加水印的时候,我们设置的是文字水印,所以需要设置字体和字号:fnt = ImageFont.truetype("/tmp/font.ttf",40)
此时,我们需要在执行之前,先将字体文件传入到 /tmp/ 文件夹下:response = client.get_object(Bucket="mytestcos-12567****", Key="font.ttf", )response['Body'].get_stream_to_file('/tmp/font.ttf')
以我的 cos 为例:for record in event['Records']: try: bucket = record['cos']['cosBucket']['name'] + '-' + str(appid) key = record['cos']['cosObject']['key'] key = key.replace('/' + str(appid) + '/' + record['cos']['cosBucket']['name'] + '/', '', 1) download_path = '/tmp/{}'.format(key) upload_path = '/tmp/new_pic-{}'.format(key) # 下载图片 try: response = client.get_object(Bucket=bucket, Key=key, ) response['Body'].get_stream_to_file(download_path) except CosServiceError as e: print(e.get_error_code()) print(e.get_error_msg()) print(e.get_resource_location()) # 图像增加水印 add_word(download_path, upload_path) # 图像上传 response = client.put_object_from_local_file( Bucket=to_bucket, LocalFilePath=upload_path.decode('utf-8'), Key=("upload-" + key).decode('utf-8') ) except Exception as e: print(e)
此处说明一下,为什么要有两个存储桶?# -*- coding: utf-8 -*-from PIL import Image, ImageFont, ImageDrawfrom qcloud_cos_v5 import CosConfigfrom qcloud_cos_v5 import CosS3Clientfrom qcloud_cos_v5 import CosServiceErrorfrom qcloud_cos_v5 import CosClientErrorappid = ** # 请替换为您的 APPIDsecret_id = ***' # 请替换为您的 SecretIdsecret_key = **' # 请替换为您的 SecretKeyregion = u'ap-chengdu' # 请替换为您bucket 所在的地域token = ''to_bucket = 'tobucket-12567***' # 请替换为您用于存放压缩后图片的bucketconfig = CosConfig(Secret_id=secret_id, Secret_key=secret_key, Region=region, Token=token)client = CosS3Client(config)response = client.get_object(Bucket="mytestcos-12567***", Key="font.ttf", )response['Body'].get_stream_to_file('/tmp/font.ttf')def add_word(pic_path, save_path): # 打开图片 im = Image.open(pic_path).convert('RGBA') # 新建一个空白图片,尺寸与打开图片一样 txt = Image.new('RGBA', im.size, (0, 0, 0, 0)) # 设置字体 fnt = ImageFont.truetype("/tmp/font.ttf", 40) # 操作新建的空白图片>>将新建的图片添入画板 d = ImageDraw.Draw(txt) # 在新建的图片上添加字体 d.text((txt.size[0] - 220, txt.size[1] - 80), "By Dfounder", font=fnt, fill=(255, 255, 255, 255)) # 合并两个图片 out = Image.alpha_composite(im, txt) # 保存图像 out.save(save_path)def main_handler(event, context): for record in event['Records']: try: bucket = record['cos']['cosBucket']['name'] + '-' + str(appid) key = record['cos']['cosObject']['key'] key = key.replace('/' + str(appid) + '/' + record['cos']['cosBucket']['name'] + '/', '', 1) download_path = '/tmp/{}'.format(key) upload_path = '/tmp/new_pic-{}'.format(key) # 下载图片 try: response = client.get_object(Bucket=bucket, Key=key, ) response['Body'].get_stream_to_file(download_path) except CosServiceError as e: print(e.get_error_code()) print(e.get_error_msg()) print(e.get_resource_location()) # 图像增加水印 add_word(download_path, upload_path) # 图像上传 response = client.put_object_from_local_file( Bucket=to_bucket, LocalFilePath=upload_path.decode('utf-8'), Key=("upload-" + key).decode('utf-8') ) except Exception as e: print(e)
这里面需要注意这几个参数:appid、secret_id、secret_key、to_bucket 作者介绍:腾讯云高级研发工程师刘宇
推荐阅读:
GitHub:欢迎关注:腾讯云 Serverless 团队
关键词:图片,水印,实践