時間:2023-07-03 16:45:02 | 來源:網(wǎng)站運營
時間:2023-07-03 16:45:02 來源:網(wǎng)站運營
「實踐」如何優(yōu)雅地給網(wǎng)站圖片加水?。?blockquote data-first-child data-pid="cejFFIXH">很多論壇、博客在進行圖片上傳之后,都會給自己的圖像加上水印,這樣可以證明這張圖片「屬于我」或者是「來自我的博客/網(wǎng)站」。那么使用 Serverless 技術(shù)來加水印的方法比傳統(tǒng)方法好在哪兒呢,本文將對此進行一個簡單的分享。傳統(tǒng)的加水印的方法,通常是在流程內(nèi)進行。即:{ "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": "上傳的鑒權(quán)信息" } } }, "cos":{ "cosSchemaVersion":"1.0", "cosNotificationId":"設(shè)置的或返回的 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" } } } ]}
這里面可以看到整個一個數(shù)據(jù)結(jié)構(gòu),需要注意 Records 是一個數(shù)組格式,其次就是:{ "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": "上傳的鑒權(quán)信息" } } }, "cos":{ "cosSchemaVersion":"1.0", "cosNotificationId":"設(shè)置的或返回的 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)) # 設(shè)置字體 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)
在添加水印的時候,我們設(shè)置的是文字水印,所以需要設(shè)置字體和字號:fnt = ImageFont.truetype("/tmp/font.ttf",40)
此時,我們需要在執(zhí)行之前,先將字體文件傳入到 /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 = ** # 請?zhí)鎿Q為您的 APPIDsecret_id = ***' # 請?zhí)鎿Q為您的 SecretIdsecret_key = **' # 請?zhí)鎿Q為您的 SecretKeyregion = u'ap-chengdu' # 請?zhí)鎿Q為您bucket 所在的地域token = ''to_bucket = 'tobucket-12567***' # 請?zhí)鎿Q為您用于存放壓縮后圖片的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)) # 設(shè)置字體 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)
這里面需要注意這幾個參數(shù):appid、secret_id、secret_key、to_bucket 作者介紹:騰訊云高級研發(fā)工程師劉宇
推薦閱讀:
GitHub:歡迎關(guān)注:騰訊云 Serverless 團隊
關(guān)鍵詞:圖片,水印,實踐
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。