扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1935|回复: 0
收起左侧

用 chevereto 图床的小伙伴快进来,有福利~

[复制链接]

一米阳光长工

贡献:735

金钱:276

威望:368

313

主题

322

帖子

3417

积分

发表于 2018-3-25 21:23:55 | 显示全部楼层 |阅读模式
嗯,今天本来想好好学习别人的代码的,突然看到 requests 模块,想想貌似这模块很常用的说,我竟然没用过,于是我就找了下文档看了下,嗯,光看不练是不对的,然后我就想做点什么,突然想到我每次写 hexo blog 的时候,每次要把图片截取保存到本地,然后上传到我的图床,然后拷贝链接, OMG 好烦啊,于是发现这篇文档 , 是时候造个轮子了。
下面是代码
  1. #coding=utf-8
  2. import requests
  3. import json
  4. import mimetypes
  5. from PIL import ImageGrab
  6. import datetime

  7. def upload(files):
  8.     APIKey = "YOUR API KEY"
  9.     format = "json"
  10.     url = "http://domain.com/api/1/upload/?key="+ APIKey + "&format=" + format
  11.     #files =
  12.     r = requests.post(url , files = files)

  13.     return json.loads(r.text)

  14. def formatSource(filename):
  15.     imageList = []
  16.     type = mimetypes.guess_type(filename)[0]
  17.     imageList.append(('source' , (filename , open(filename , 'rb') , type)))
  18.     print imageList
  19.     return imageList

  20. if __name__ == "__main__":
  21.     print "将图片截图或复制到剪切板中即可~~, ctrl+z 结束"
  22.     recentVal = None
  23.     while(True):
  24.         tmpValue = ImageGrab.grabclipboard()
  25.         if recentVal != tmpValue:
  26.             recentVal = tmpValue
  27.             now = datetime.datetime.now()
  28.             now = now.strftime("%Y-%m-%d %H:%M:%S")
  29.             filename = 'IMG'+ now + '.png'
  30.             if recentVal is not None:
  31.                 recentVal.save(filename, 'png')
  32.                 #filenames.append(filename)
  33.                 #recentVal = None
  34.                 print filename
  35.                 jsonData = upload(formatSource(filename))

  36.                 if jsonData['status_code'] != 200:
  37.                     print "error: " , jsonData['error']['message']
  38.                     print "status code : " , jsonData['status_code']
  39.                 else:
  40.                     print "orignal url: " , jsonData['image']['display_url']
  41.                     print "thumb url: " , jsonData['image']['thumb']['url']
复制代码

运行示例 006tKfTcgw1fbcfkytzffg30uy0lu1kx.gif

有点慢啊,因为我的服务器在国外~~
使用方法
将你的 chevereto 的 API key 拷贝到对应位置,替换 domain.com 为你自己的域名,嗯,就这样,这只是练习代码,难免有些 bug ,你懂得
其实讲道理用curl就可以弄的,但是我不会把本地的图片传到服务器上,据说要base64编码~~~sad
嗯,开年第一个轮子,大家新年快乐!



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为兴趣而生…… 立即登录 立即注册
TOP

用 chevereto 图床的小伙伴快进来,有福利~

嗯,今天本来想好好学习别人的代码的,突然看到 requests 模块, ...

温馨提示:手机扫描二维码继续浏览

快速回复 返回顶部 返回列表