用 Python 来上传图片至 ChevertoFree

发布于 / Code / 0 条评论

搭建了 ChevertoFree 来作为图床后发现上传还需要打开网页过于麻烦,看到关于 API v1 的文档后决定写个脚本来匿名上传图片。

Python3.7 + MacOS10.14

  • 使用 requests
  • 自动获取剪切板图片
  • 上传成功后返回图片链接

代码

#coding=utf-8
import requests
import json
import mimetypes
from PIL import ImageGrab
import datetime

def upload(files):
    APIKey = "YOUR API KEY"
    format = "json"
    url = "https://yourdomian/api/1/upload/?key="+APIKey+ "&format=" + format
    #files =
    r = requests.post(url , files = files)

    return json.loads(r.text)

def formatSource(filename):
    imageList = []
    type = mimetypes.guess_type(filename)[0]
    imageList.append(('source' , (filename , open(filename , 'rb') , type)))
    print (imageList)
    return imageList

if __name__ == "__main__":
    print ("将图片截图或复制到剪切板中即可, ctrl+z 结束")
    recentVal = None
    while(True):
        tmpValue = ImageGrab.grabclipboard()
        if recentVal != tmpValue:
            recentVal = tmpValue
            now = datetime.datetime.now()
            now = now.strftime("%Y-%m-%d %H:%M:%S")
            filename = 'IMG'+ now + '.png'
            if recentVal is not None:
                recentVal.save(filename, 'png')
                #filenames.append(filename)
                #recentVal = None
                print (filename)
                jsonData = upload(formatSource(filename))

                if jsonData['status_code'] != 200:
                    print ("error: " , jsonData['error']['message'])
                    print ("status code : " , jsonData['status_code'])
                else:
                    print ("orignal url: " , jsonData['image']['display_url'])
                    print ("thumb url: " , jsonData['image']['thumb']['url'])
转载原创文章请注明,转载自: 风过不留痕 » 用 Python 来上传图片至 ChevertoFree
Not Comment Found