V2版本官网:萌部随机图片v2测试
URL:
https://service-djbqi6pz-1306777571.sh.apigw.tencentcs.com
a1版本(推荐): http://service-ki5kzs0b-1306777571.sh.apigw.tencentcs.com/Mobuv2
默认的输出格式是jpeg,可以使用form参数来修改输出格式,现在测试jpeg格式最快,全国响应都在0.5s左右
但是需要注意的是,因为云函数需要在访问的时候开启一个实例,所以第一次访问会比较慢
URL: https://service-djbqi6pz-1306777571.sh.apigw.tencentcs.com/release/index.py?form=jpeg
所以特别推荐使用webp格式!!!如果不用,那我就强制改成必要用吧(嘻嘻嘻嘻
还支持id参数,例子:
这次使用直接输出图片二进制流,避免图片直链,保证可用性
源代码:
import KamitaTomoe.output as output
# import KamitaTomoe.html as html
import KamitaTomoe.gain as gain
# import KamitaTomoe.session as session
chdir()
from PIL import Image
from io import BytesIO
from random import choice,randint
import os
import json
url = 'http://127.0.0.1:8888/?'
def GetAllFileNamesUnderTheDirectory(): #获取目录下所有文件名
root = './img'
path = os.path.join(root)
filenames = os.listdir(path)
pathnames = [os.path.join(path, filename) for filename in filenames]
return pathnames
def ImageZoom(width,p_img): #图像缩放
'''Parameters:
Width: width of the target image
p_ Img: PIL object'''
widths, height = p_img.size # 获取宽高
fdl = width/widths #缩放率
p_img = p_img.resize((int(widths*fdl), int(height*fdl)), Image.ANTIALIAS)
return p_img
def Picture_stream():
def load(id = None):
pathnames = GetAllFileNamesUnderTheDirectory()
if(id != None):
id = int(id)
#choice(pathnames) 随机
try: #id正确的情况
with open(pathnames[id], 'rb') as f:
im = f.read()
except: #id错误的情况
output.echo('id错误', 'text/html')
else:
with open(choice(pathnames), 'rb' ) as f:
im = f.read()
return Image.open(BytesIO(im)) # BytesIO实现了在内存中读写Bytes
#->return p_img
def PilTob(p_img,mode,widths=1920): # PIL 转二进制
b_img = BytesIO() # 创建一个空的Bytes对象
ImageZoom(widths,p_img).save(b_img, format=mode) # 保存为jpg格式
return b_img.getvalue()
if(gain.gets('id') != None):
p_img = load(gain.gets('id'))
else:
p_img = load()
if(gain.gets('form') != None):
try:
# 格式输入正确
output.echo(PilTob(p_img,gain.gets('form')),f'''image/{gain.gets('form')}''')
except:
output.echo('格式输入错误', 'text/html')
else:
output.echo(PilTob(p_img,'webp'),'image/webp')
def json_output():
pathnames = GetAllFileNamesUnderTheDirectory()
outputdict = {'url':f'{url}'} #需要输出的字典
changedict = {}
if(gain.gets('id') != None):
changedict['id'] = gain.gets('id')
else:
changedict['id'] = randint(0,len(pathnames)-1)
if(gain.gets('form') != None):
changedict['form'] = gain.gets('form')
else:
changedict['form'] = 'webp'
for k,v in changedict.items():
outputdict[k] = v
outputdict['url'] += f'{k}={v}&'
output.echo(json.dumps(outputdict),'text/json')
if(gain.gets('output')=='json'):
json_output()
elif(gain.gets('output')=='TotalNumberOfImages'): #图像总数
output.echo(len(GetAllFileNamesUnderTheDirectory()),'text/html')
else:
Picture_stream()
webp好用!(´இ皿இ`)
清晰度好高,文件还挺小