Why the need?

I often use Markdown to write something, and images are essential in my articles. Under normal circumstances, it is first to save the drawing to a local place, then manually upload the picture to OSS (such as seven Niuyun), and finally copy the external link address to add to the article. Another scenario is watermarking. It is not easy to be original. Sometimes, a blog article written on the first night will appear on a public account the next day and apply for original protection. At this time, if there is a special watermark on the picture, the original copy of the article can be found. Although this kind of infringement cannot be completely solved, it also increases the cost of plagiarists.

The specific implementation

As for the concrete implementation, I considered several issues:

  1. After the file download, can immediately output the change of the folder;
  2. The downloaded files can be marked with a preset watermark (this OSS will definitely provide);
  3. Upload the file to OSS according to the output of the new file name (image name);
  4. Returns the external link address of the image file.

Tools involved:

  • OS: macOS
  • Picture bed: Seven niuyun
  • File monitoring tool: fswatch

The author sorted out the storage SDK of Qiuniuyun, which is mainly upload & pretransfer persistence, and upload the image to the corresponding bucket with watermarking. This is just a small tool, so far has been able to meet my needs.

File monitoring tool: fswatch

Inotify-tools can be used to detect changes to folders and files in Linux.

Fswatch is a synchronization tool that uses the Mac OS X FSEvents API and can also be used on BSD and Debian operating systems.

Install using Homebrew:

brew install fswatch
Copy the code

Monitor the /User /usr/downloads folder:

fswatch /User/usr/Downloads
Copy the code

When the contents of the /User /usr/downloads file change, output the list of changed files. Such as:

/Users/user/Downloads/PlatformTransactionManager.jpg
Copy the code

Of course, there are other uses of fswatch that I won’t expand on here.

Create buckets and styles

First of all, you need to register seven niuyun account, click on the registration channel registration (I here is not specifically advertising, did not charge any advertising fees. .

Second, create a bucket. As shown below, the author named it BL-bucket.

In the diagram above, also can see the author bind the domain name http://image.blueskykong.com, this can choose, if it is not binding, you can use the test domain names. After binding the domain name, remember to set the domain name as the default domain name of the external chain.

This is done so that the script returns the last external link address (the rule I defined is to concatenate the default domain name + filename of the external link).

Then, set the watermarking style, the author added the text watermarking public number: AOHO Qiusuo in the lower right corner of the picture. Of course, you can also make other style Settings on the picture, such as zooming in and out of the picture, setting the length and width, etc., the reader can customize according to their needs. After setting, it will look like the picture below:

What we really need is the processing interface generated at the end, which we’ll use in our upload script.

scripting

In the above steps, we first recorded the new image name of the specific file, and then set our bucket, external chain domain name and watermark style. Now let’s do the coding.

After starting FSwatch, output the changed file record to the specified file, and then there are three main steps:

  • Our script is based on Python, install the Python SDK of Qiuniuyun, refer to the official website Python SDK for details
  • Read the value of the change in the specified file record, here I specify to read the last line (in fact, the change is active, so only the last line is needed for the new image file)
  • Upload the file, using the seven niuyunUpload & pretransfer persistence.
# -*- coding: utf-8 -*-
# flake8: noqa

from qiniu import Auth, put_file, etag, urlsafe_base64_encode
import qiniu.config
from qiniu import BucketManager
from optparse import OptionParser
# Watermark upload function
def watermark_add(filename):
	# Space to upload
	bucket_name = 'bl-bucket'

	# File name saved after uploading to Seven Cows
	arr = filename.split("/")
	
	key = arr[len(arr)- 1]
	# Set image thumbnail parameters
	fops = 'imageView2/0/q/75|watermark/2/text/5YWs5LyX5Y-377yaYW9ob-axgue0og==/font/5b6u6L2v6ZuF6buR/fontsize/400/fill/IzAwMDAwMA= =/dissolve/50/gravity/SouthEast/dx/10/dy/10'

	# by adding '| saveas' parameter, specify the file after the processing of the bucket and key, does not specify a default is saved in the current space, bucket_saved for target bucket, key_saved for target key
	encode_str = bucket_name + ":" + key

	saveas_key = urlsafe_base64_encode(encode_str)

	fops = fops+'|saveas/'+saveas_key

	access_key = 'xxx'
	secret_key = 'xxx'

	Create an authentication object
	q = Auth(access_key, secret_key)

	Generate upload Token, can specify expiration time, etc
	# Specify FOBs and pipeline in upload policy
	policy={
	  'persistentOps':fops
	 }

	token = q.upload_token(bucket_name, key, 3600, policy)

	The local path to upload the file
	localfile = filename

	ret, info = put_file(token, key, localfile)
	print("http://image.blueskykong.com/" + key)
	assert ret['key'] == key
	assert ret['hash'] == etag(localfile)
	pass

# Direct upload function
def upload_pic(filename):.# Simple, omitted here

Get the changed file name
def get_upload_name(fname):
  with open(fname, 'r') as f:  # Open file
    lines = f.readlines() Read all rows
    first_line = lines[0] Take the first row
    last_line = lines[- 1] # take the last row
    return last_line

fname='nohup.out'
if __name__ == '__main__':
  l = get_upload_name(fname)
  l=l.replace("\n"."")
# print (l)
  watermark_add(l)
# print (upload_pic(l))
Copy the code

The preceding script is sufficient. You need to set access_key, secret_key, fname (file name output by fswatch), and bucket_name. The secret keys can be found at the Personal Center:

test

Start fswatch listening/Users/user/Documents/PIC /, and output records to nohup. The out file.

nohup fswatch /Users/user/Documents/pic/ &
Copy the code

Fswatch is constantly listening in background processes. I also wrote a bash command that could be written as simple as this:

#! /bin/bash
echo "uploading pic..."
echo "url is : "
python upload.py
exit 0
Copy the code

After each image upload, execute this command to get the following output:

uploading pic...
url is :
http://image.blueskykong.com/secret-qiniu.jpg
Copy the code

This is the output of the script executed after the local screenshot has been saved. http://image.blueskykong.com/secret-qiniu.jpg is the address we upload pictures outside the chain.

conclusion

A small tool to share, suitable for MAC under markdown writing partners, to reduce some tedious operations. At present, can meet the needs of the author, there is no high-end place. If you have any improvements or better tools, feel free to share them in the comments. Of course, if there is not clear, you can refer to git project at https://github.com/keets2012/Sync-Pic.git.

Seven NiuYun registered address: https://portal.qiniu.com/signup?code=3lffq8tzqxc9e

Subscribe to the latest articles, welcome to follow my official account

reference

OS X automatically detects and synchronizes folder changes using FSWatch +rsync