摘要
在写博客的过程中经常要插入图片,许多博客平台提供了图片上传的服务,但是不能保证长期有效,不同平台还不能通用,所以要通过搭建统一的图床来实现。有用服务器作为图床和第三方图床,前者限制多,需要备案,后者不是很可靠,而用代码托管平台做图床,既稳定可靠没有很大限制,而且数据实现同步,即使云端的数据丢失了,本地还有备份,而在中国,为了提升访问速度,我们并不选取GitHub做图床,而是选择了Gitee,本文将使用Python实现对上传的图片自动压缩,自动编码,以及自动推送到远程仓库,但由于Gitee的限制,最后仍需要手动对Gitee Pages进行更新
新建仓库
如果没有帐户,先进入Gitee主页注册账户,接着新建仓库,名称为resource ,路径为res (使用res是为了使图片链接看起来更加简洁)
新建完成后需要初始化Readme.md 文件,同时复制地址(为了使用Gitee Pages服务):

然后打开服务选项:

点击Gitee Pages:

点击“启动”启动服务:

克隆仓库
在计算机中找一个位置建一个文件夹,在文件夹中使用Git Bash 输入命令克隆仓库到本地:
git clone https://gitee.com/xxx/xxx.git
克隆完成后在本地生成了一个名为res 的文件夹,此时可以删除文件夹中的Readme.md 文件,在res 文件夹中新建空文件夹upload_images
在与res 同级的目录下新建空文件夹temp 用于存放待上传的文件:

获取TinyPng的"API Key"
进入TinyPng的主页(https://tinypng.com/),在右上角进行注册:  输入邮箱地址:

打开邮箱验证,点击邮件中的"Log in with magic link",点击刚刚注册的地方,选择"Account page":

注册成功后会出现如下页面,启用并复制"API Key"

TinyPng每月支持免费转换500张图片,并且重复的图片多次压缩只算做一次,这对图片插入量一般的人来说已经足够了,如果觉得一个月500张不够,又不想花钱,可以多注册几个号
安装需要的Python包
脚本需要用到两个包:tinify 和GitPython
打开cmd命令提示符,输入安装指令:
pip install --upgrade tinify
pip install gitpython
如果失败可以尝试本地安装
编写Python脚本
在与res 同级的目录下新建upload.py :
[
用python的IDE打开该py文件写入如下代码:
import random
import time
import os
import shutil
from git import Repo
import tinify
repo = Repo('./res')
tinify.key = '****************'
exts = ['.png','.jpg','.bmp']
compression = ['.png','.jpg']
srcdir = './temp'
dstdir = './res/upload_images'
url = 'https://xxx.gitee.io/res/upload_images/'
def random_hex(length):
result = hex(random.randint(0,16**length)).replace('0x','').lower()
if(len(result)<length):
result = '0'*(length-len(result))+result
return result
def auto_code(ext):
while True:
name = random_hex(8)
result = os.path.join(dstdir,name + ext)
if not os.path.exists(result):
break
return result
def main():
f = open('./output.txt','w')
list = os.listdir(srcdir)
for i in range(0,len(list)):
srcpath = os.path.join(srcdir,list[i])
if not os.path.isfile(srcpath):
continue
ext=os.path.splitext(srcpath)[-1].lower()
if ext not in exts:
continue
dstpath = auto_code(ext)
if ext in compression:
tinify.from_file(srcpath).to_file(srcpath)
shutil.move(srcpath,dstpath)
print('成功压缩并移动:' + os.path.basename(srcpath))
else:
shutil.move(srcpath,dstpath)
print('成功移动:' + os.path.basename(srcpath))
f.write(os.path.basename(srcpath) + ': + ')\n')
f.close()
print('输出文件output.txt已生成')
print(repo.git.add('--all'))
print(repo.git.commit('-m upload images'))
print(repo.remote().push('master'))
print('已推送至远程仓库,python即将退出')
time.sleep(1)
if __name__ == '__main__':
main()
测试功能
将图片复制到temp 文件夹,运行upload.py ,在其运行完毕后打开Gitee Pages服务进行更新,然后打开output.txt ,复制里面的Markdown语句至Markdown编辑器即可看见图片
|