前言

之前换博客的时候提到,很大一原因是因为 typecho 上传 markdown 的时候,上传图片很很很不方便。换用 hexo 之后,其实并没有得到太大改善。后来用上了 PicGo 加上 github 图床,剪切板的图片可以用快捷键一键上传到 github 并且得到图片链接然后改为 markdown 格式,确实很好用。但是我记笔记大部分都是本地,很多不发博客的笔记完全没必要这样做,纯属增加劳动量。所以今天想发篇博客的时候看着那几十张图片,一个个拖、改,实在难以下手。于是,我想,能不能把要发的 markdown 一键上传图片,并且自动将里面的本地图片链接改成图床的链接呢?于是便有了这篇文章。

pypicgo

这种小量的工具还是python方便,我先想到的是PicGo有没有命令行版本,但并未发现。然后便看到了一个python包,pypicgo
试了一下,这就是一个单纯的命令行工具,不能直接python内引用函数
于是…就只能,尝试改改这个包了

这个 uploade.py 名字就已经很明显了,大部分的外层逻辑也都在这

这两个参数就是命令行传参的两个参数,file 是图片文件,这里我改成了m

1
parser.add_argument('-m', '--mdfiles')

大体逻辑其实很简单,就是正则匹配到 markdown 文件的本地图片路径并存入一个数组,然后遍历上传这些图片

这里我也就加了两个函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def mdFileFindImg(mdFile):
files = []
for line in mdFile:
if line.find('![') != -1:
start = line.find('(')
end = line.find(')', start)
files.append(line[start+1:end])
return files



def mdFileChange(mdFile, oldFilepath, newFilepath):
if mdFile.find(oldFilepath) != -1:
potision = mdFile.find(oldFilepath)
start = mdFile.find('![', potision - 30, potision)
end = mdFile.find(')', potision)
mdFile = mdFile.replace(mdFile[start:end + 1], '![](' + newFilepath + ')')
return mdFile

第一个用来正则匹配路径,第二个用来将 本地路径 改为 图床路径

所以很明显,更关键的问题是如何找到这个 图床路径,这个结果在运行的时候其实会打印出来,但打印的代码在

我没想到什么好的方法能将这个 message 传到 upload.py 中,之前其实也遇到过这种问题,最后我的解决一般都是序列化成文件,或者直接写入文件,这里我就用了后者的办法

(PS:这里的 message ,是所有文件上传完后打印出来,打印的是所有的链接

1
2
3
4
5
6
7
8
https://raw.githubusercontent.com/xlccccc/Image/master/hexoblog/liunxb4b959368a97541ee99cb9ce55f94e74chenghaiwen20230330220944-image-20230327163612053.png

https://raw.githubusercontent.com/xlccccc/Image/master/hexoblog/liunxa695cf55618458b21f863dfe8adcfaa9chenghaiwen20230330220948-image-20230322171917611.png

https://raw.githubusercontent.com/xlccccc/Image/master/hexoblog/liunxd4e8406dd0eaa317d3a413182c18044fchenghaiwen20230330220950-image-20230322172032540.png

https://raw.githubusercontent.com/xlccccc/Image/master/hexoblog/liunx584e7aec0dac759ce9ee3d7daa45b930chenghaiwen20230330220952-image-20230322172055370.png

比如这样子,所以得清除一下空行,然后每个链接占一行这样子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import sys, os
from typing import List
from pypicgo.core.base.plugin import FinallyPlugin
from pypicgo.core.base.result import Result


class TyporaPlugin(FinallyPlugin):
name = 'Typora'

def execute(self, results: List[Result]):
urls = []
for result in results:
if result.status:
urls.append(result.remote_url)
if len(urls) > 0:
message = os.linesep.join(urls)
sys.stdout.write(f'Upload Success:{os.linesep}message{os.linesep}')
lines = [line for line in message.splitlines() if line.strip()]
f = open('url.txt', 'w')
f.write('\n'.join(lines))
f.close()

然后直接上传 markdown 就ok啦

但是有可能图库上传了但是文件还没改,和python有关?如果这样了,就得重新上传一遍