Automating Image Hosting for Markdown

I used to put my images on sm.ms, a public image host with an open API. I even wrote a script to upload the images and replace the links in my Markdown. The service’s limits became frustrating, though: uploads were restricted per minute and capped at 20 images per hour. I decided to host them in my own GitHub repository instead and consider a VPS later.

I wrote another script to automate the new workflow: paste image -> put image in git folder -> run automation script. The script handles the upload and link replacement. Here is how I set it up.

First, set up a directory in a GitHub repository to hold the images:

image-20191201161807225.png

Then use git clone to make a local copy:

image-20191201161815623.png

Put your images in that local directory. In typora, you can also set it as the automatic image-save location; that skips the manual copy and lets you run the script immediately.

Open the script and adjust the paths and repository settings for your own setup:

image-20191201161912963.png

I marked the settings that need changing in comments in the code below.

Once those settings are in place, running the script completes the upload and link replacement. Here is the automation code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import re
import os
def parseText(textpath):
f = open(textpath,'r+',encoding = 'utf-8')
text = str(f.read())
f.close()
return text

def getPicPath(text):
#根据你的图片自己设置,不同版本不一样
srcPic = re.findall(r'\!\[image-\d*\]\(.*\)',text)
dst = []
for i in srcPic:
str1 = re.findall('\/.*\)',i)[0]
str1 = str1[1:-1]
dst.append(str1)
return srcPic,dst

def replaceText(text,src,dst):
for i in range(len(src)):
dst[i] = '!['+dst[i]+']('+'https://raw.githubusercontent.com/xxxxx/xxxxx/'+dst[i]+')'
#中间的网址替换为https://raw.githubusercontent.com/你的用户名/你的仓库/你的分支/你的目录/
text = text.replace(src[i],dst[i])
return text

def rewrite(textpath,text):
f = open(textpath,'w+',encoding='utf-8')
f.write(text)
f.close()

def main():
#自己写markdown的目录
rootpath = 'C:/Users/周半仙/Desktop/ComputerSecurity/'
#自己写markdown的文件名,注意斜线
textpath = rootpath+'实验三_副本.md'
text = parseText(textpath)
src,picdst = getPicPath(text)
text = replaceText(text,src,picdst)
payload = 'git add . && git commit -m "auto upload" && git push'
#自己写你的图片的本地位置
os.chdir('D:\\imageBed\\imageBed')
os.system(payload)
main()