background

I’ve been messing around with the Hexo blog for a while, deploying Github Pages, setting up my own domain forwarding, and adding HTTPS, as if I had everything but blogging. However, finding blog images was a problem because when markDown added images, I wanted to use CDN instead of local images.

So I investigated some cloud service providers that can be used as graph bed, such as Qiniu, SM.MS and Tencent Cloud. After comparison, I found that Qiniu does not support HTTPS, SM. Ms is completely free, but the function seems to be less, teng Cloud has free space of dozens of GIGABytes (I forget the specific amount) but also provide HTTPS. Well, let’s use Tencent Cloud.

Map bed selection, then upload map bed tools? They say iPic is a map bed artifact, and recently it also supports Tencent Cloud, but it needs to be paid for. What I need is a free version, looking for a long time also can’t find support Tencent cloud graph bed tool. As a coder, how can I tolerate this? I vaguely remember a friend’s blog wrote about using Automator to upload pictures to sm.ms, so I borrowed (copy), there is this article. The difference here is that I am using the Python SDK of Tencent Cloud for uploading.

Train of thought

Uploading images using Automator

  • Click on the local image, right click on the service created by Automator
  • Call the pre-written script for the upload
  • Write the URL to the clipboard after upload
  • Paste and enjoy directly in the MarkDown editor

Implementation steps

Open Automator and select New Service:

Then in “Utilities”, find “Copy to clipboard” and drag it to the right workflow, so that when we select an image, the local path of the image will be set to the clipboard:

We need to do actual testing during the service creation process, so we can add the “Get Specified Access (Finder) project” utility to the workflow on the right, at the top, and add a few images for testing (which we need to remove later), as shown below:

Then click the run button in the upper right corner. After running, check your clipboard contents, and you will find that the clipboard contents are exactly the path of the picture.

Now the picture path has, add a shell script workflow, in the script to get the picture path inside the clipboard, and then upload, and then upload the Tencent Cloud picture address into the clipboard, it is ok.

Add the “Run shell scripts” workflow to the right as the third workflow and select Python as the default shell, as shown below:

All the Python code in the figure above does is upload the image and set the contents of the clipboard as follows:

# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import os
import subprocess

# upload tencent cloud need related configuration, can see here: https://console.cloud.tencent.com/cam/capi
secret_id = 'your_cos_secret_id' # Secret_id from Tencent Cloud
secret_key = 'your_cos_secret_key' Insert secret_key of Tencent Cloud here
app_id = 'your_app_id' # App_id here
region = 'your_region' # Here fill in the region of the object store
token = ' '  To use a temporary key, you need to pass a Token, which is left blank by default
bucket_name = 'your_bucket_name'
bucket = bucket_name + The '-' + app_id  # Bucket consists of bucketname and appID
legal_extensions = ['.jpg'.'.jpeg'.'.png'.'gif']


Get the contents of the clipboard
def getClipboardData(a):
    p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)
    retcode = p.wait()
    data = p.stdout.read()
    return data


Set clipboard contents
def setClipboardData(data):
    p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
    p.stdin.write(data)
    p.stdin.close()
    retcode = p.wait()


# Determine whether the extension is valid
def validate_image(path):
    extension = os.path.splitext(path)[1]
    if extension in legal_extensions:
        return True
    else:
        return False


# upload to Tencent Cloud
def upload(file_name, filepath):
    config = CosConfig(Appid=app_id, Secret_id=secret_id, Secret_key=secret_key, Region=region, Token=token)
    # Get the client object
    client = CosS3Client(config)

    with open(filepath, 'rb') as fp:
        response = client.put_object(
            Bucket=bucket,
            Body=fp,
            Key=file_name,
            StorageClass='STANDARD',
            ContentType='text/html; charset=utf-8'
        )
        # print response


def main(a):
    contents = getClipboardData().split("\n")

    uploaded_url = ""
    for path in contents:
        if validate_image(path):
            file_name = os.path.basename(path)
            upload(file_name, path)
            
            # splice into markDown image link format
            uploaded_url += '! [] (' + 'https://' + bucket + '.cos.' + region + '.myqcloud.com/' + file_name + ")\n"
	
	# Set url to clipboard
    setClipboardData(uploaded_url)


main()

Copy the code

The amount of code is not much, and the implementation of upload function is using the official SDK. How to install the SDK and how to use it, please refer to the official documentation

Tips: Not only can you step through this run, but you can also view the program output for testing:

The upload function has been implemented here, and it would be better to add another one to give a hint after the upload is complete.

Add the “Show Notifications” workflow to the right workspace, set the notification content, and then execute to see the notification prompt

Now that the functionality is in place, remove the first workflow, “Get specified Finder item.” Save the service and give it a name:

Then find a random picture, right-click the menu, you will see the service we just created, no accident, you can use normally:

Where do you go next time you want to edit this service? ~/Library/Services: ~/Library/Services

> ls ~/Library/ServicesUpload information to Tencent Cloud. WorkflowCopy the code

At this point, the automator is done uploading images. The downside is that you can only operate on image files on disk. The screenshot cannot be operated on. In theory, as long as you can get the contents of the clipboard, it is possible to upload screenshots.

Reference:

  • Upload images to sm.ms using Automator
  • Tencent Cloud Object Storage Python SDK documentation