import base64, os
import time
import requests
DIR_PATH = './image/'
os.makedirs(DIR_PATH, exist_ok=True)
r = requests.get(IMAGE_URL)
img_bytes = r.content
base64_str = base64.b64encode(img_bytes).decode()
//保存image
def save_image(code, img_bytes):
with open('{}{}_{}.png'.format(DIR_PATH, code, int(round(time.time() * 1000))), 'wb') as f:
f.write(img_bytes)
//将image转成base64_str保存 逐行写在一个文件中
//形如code_base64_str
def save_text(code, base64_str):
with open('{}{}.txt'.format(DIR_PATH, 'base64'), 'a+') as f:
f.write('{}_{}\n'.format(code, base64_str))
//将base64_str转成image
def base64_2_image():
with open('{}{}.txt'.format(DIR_PATH, 'base64'), 'r') as f:
for line in f.readlines():
with open('{}{}_{}.png'.format(DIR_PATH, line.split('_')[0], int(round(time.time() * 1000))), 'wb') as f:
f.write(base64.b64decode(line.split('_')[1].rstrip('\n')))
'r':读
'w':写
'a':追加
'r+' == r+w(可读可写,文件若不存在就报错(IOError))
'w+' == w+r(可读可写,文件若不存在就创建,并从开头开始编辑,即原有内容会被删除)
'a+' ==a+r(可追加可写,文件若不存在就创建)
对应的,如果是二进制文件,就都加一个b:
'rb' 'wb' 'ab' 'rb+' 'wb+' 'ab+'