Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Serverless to watermark website images

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use Serverless to watermark website pictures". In daily operation, I believe that many people have doubts about how to use Serverless to watermark website pictures. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to use Serverless to watermark website pictures". Next, please follow the editor to study!

The traditional method of watermarking is usually carried out in the process. That is:

Although this is feasible, it will undoubtedly increase the pressure on a single request and the server. If it is in the case of high concurrency, or when multiple people upload multiple large images, it may cause excessive effect of their own server resources.

If it fails in the process of watermarking, it may lead to the failure of image storage and the loss of data, which is not rational. So then someone made the following improvements:

The advantage of this is that we can quickly store the picture, and then process the task list through a separate processing thread. On the one hand, it can ensure that we store the picture uploaded by the user immediately, and it can be displayed. At the same time, we can also carry out watermark processing in the background. After processing, we can overwrite the picture or store it separately. When the user needs to read the picture, It can be automatically changed into a watermarked picture.

This approach may be a little more complex than the former, but it is actually a more stable data, less server-side pressure, and more controllable operation. However, this whole process still has to be done on your own server. Now that many people store images and other resources in Tencent Cloud's COS, can you combine some COS triggers with the cloud function SCF to implement a process that does not add watermarks to your own servers?

This article will take the function template (Python language) of Tencent Cloud function SCF as an example for a simple sharing.

New function in ▎ experiment

In the serverless cloud function, select the template function:

By searching for the "image" keyword, select the image compression, and determine the establishment. After saving, click on the function code to write the code.

COS trigger

Some people may not know much about COS triggers, so you can click configure to familiarize yourself with COS trigger styles:

You can see the following:

{"Records": [{"event": {"eventVersion", "eventSource": "qcs::cos", "eventName": "cos: ObjectCreated: *", "eventTime": 1501054710, "eventQueue": "qcs:0:cos:gz:1251111111:cos" "requestParameters": {"requestSourceIP": "111.111.111.111", "requestHeaders": {"Authorization": "uploaded authentication information"}, "cos": {"cosSchemaVersion": "1.0"," cosNotificationId ":" set or returned 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": "Custom meta", "x-image-test": "Custom meta"} "url": "access the origin server url of the file"}]}

You can see the entire data structure here. Note that Records is an array format, followed by:

"cosBucket": {"name": "bucketname", "appid": "appId", "region": "gz"}

This is triggered by the bucket.

"cosObject": {"key": "/ appid/bucketname/DSC_0002.JPG", "size": 2598526, "meta": {"Content-Type": "text/plain", "x-cos-meta-test": "Custom meta", "x-image-test": "Custom meta"}, "url": "Origin server url accessing files"}

The key in this is the name of the new file created in the above bucket.

Therefore, according to our actual situation, we can simply modify the above to our format for testing (in production, this is an automatically generated trigger format, and we do not need to modify it. We modify it just for testing.

{"Records": [{"event": {"eventVersion", "eventSource": "qcs::cos", "eventName": "cos: ObjectCreated: *", "eventTime": 1501054710, "eventQueue": "qcs:0:cos:gz:1251111111:cos" "requestParameters": {"requestSourceIP": "111.111.111.111", "requestHeaders": {"Authorization": "uploaded authentication information"}, "cos": {"cosSchemaVersion": "1.0"," cosNotificationId ":" set or returned ID " "cosBucket": {"name": "mytestcos", "appid": "appId", "region": "gz"}, "cosObject": {"key": "test.png", "size": 2598526 "meta": {"Content-Type": "text/plain", "x-cos-meta-test": "Custom meta", "x-image-test": "Custom meta"} "url": "access the origin server url of the file"}]}

Here I mainly modify my cosBucket-name: mytestcos, and key: test.png

Code modification

The reason for using the existing template is that there are related package such as PIL and qcloud_cos_v5 in this template, and these two package are exactly what we are going to need, so that we can save the process of packaging functions and only need to make simple modifications.

Add a watermark:

Def add_word (pic_path, save_path): # Open the picture im = Image.open (pic_path). Convert ('RGBA') # create a new blank picture with the same size as the open picture txt = Image.new (' RGBA', im.size, (0,0,0,0)) # set the font fnt = ImageFont.truetype ("/ tmp/font.ttf") 40) # Operation New Blank Picture > > add the newly created picture to the artboard d = ImageDraw.Draw (txt) # add fonts d.text ((txt.size [0]-220, txt.size [1]-80), "By Dfounder", font=fnt, fill= (255,255,255,255)) # merge the two pictures out = Image.alpha_composite (im) Txt) # Save image out.save (save_path)

When adding a watermark, we set the text watermark, so we need to set the font and font size:

Fnt = ImageFont.truetype ("/ tmp/font.ttf", 40)

At this point, we need to pass the font file to the / tmp/ folder before execution:

Response = client.get_object (Bucket= "mytestcos-12567****", Key= "font.ttf",) response ['Body'] .get_stream_to_file (' / tmp/font.ttf')

Take my cos as an example:

Then, the next step is to resolve the triggered event, including obtaining the newly created image name, pulling it from the COS, putting it locally, watermarking, etc., and uploading it back to the new 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) # download picture 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 ()) # Image add watermark add_word (download_path Upload_path) # Image upload 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)

Explain here, why there are two buckets?

Because we want to use a bucket as a "tool" to trigger the SCF function, if we write the watermark result back to this bucket again, then the image after the watermark will be watermarked again without additional judgment and processing, causing a bad cycle over and over again, so building two buckets here can reduce the difficulty, protect performance and reduce the birth of BUG.

The complete code is as follows:

#-*-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 = * * # Please replace with your APPIDsecret_id = * * # Please replace with your SecretIdsecret_key = * * # Please replace with your SecretKeyregion = bucket Chengdu' # Please replace with the region where your bucket is located token =''to_bucket =' tobucket-12567***' # Please replace it with you Bucketconfig = CosConfig (Secret_id=secret_id) used to store compressed images 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): # Open the picture im = Image.open (pic_path). Convert ('RGBA') # create a new blank picture Txt = Image.new ('RGBA', im.size, (0,0,0,0)) # set font fnt = font ("/ tmp/font.ttf", 40) # operate the newly created blank picture > > add the newly created picture to the artboard d = ImageDraw.Draw (txt) # add the font d.text ((txt.size [0]-220) to the newly created picture Txt.size [1]-80), "By Dfounder", font=fnt, fill= (255,255,255,255) # merge two images out = Image.alpha_composite (im, txt) # Save image 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) # download picture 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 ()) # Image add watermark add_word (download_path Upload_path) # Image upload 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)

You need to pay attention to these parameters: appid, secret_id, secret_key, to_bucket

The sources of these parameters are as follows:

Secretid,secretkey needs to be obtained here:

test

I have already uploaded a test picture in this bucket, the name is: test.png

The picture looks like this:

Then let's do a test:

As you can see, the test has been successful, so let's take a look at our target bucket:

You can see that a picture has been generated successfully:

You can see the watermark added in our code in the lower right corner of the image:

At this point, the study on "how to use Serverless to watermark website images" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report