feat:将图像处理库从PIL改为OpenCV以优化性能

This commit is contained in:
Kakune55 2024-05-09 11:26:31 +08:00
parent e44fa7fb8e
commit 007645e94d
3 changed files with 17 additions and 29 deletions

40
file.py
View File

@ -1,9 +1,10 @@
import shutil, os, zipfile, io
import shutil, os, zipfile, io, cv2, numpy as np
import db.file, app_conf
from PIL import Image
app_conf = app_conf.conf()
def init():
paths = ("inputdir", "storedir", "tmpdir")
for path in paths:
@ -66,27 +67,14 @@ def raedZip(bookid: str, index: int):
return str(e), ""
def thumbnail(input,size=(420,600)):
im = Image.open(io.BytesIO(input))
del input
newimg = im.convert('RGB')
im.close()
newimg.thumbnail(size)
output_io = io.BytesIO()
newimg.save(output_io,format='WEBP')
newimg.close()
output_io.seek(0)
return output_io
def imageToWebP(input,size=(2100,3000)):
with Image.open(io.BytesIO(input)) as img:
newimg = img.convert('RGB')
img.close()
output_io = io.BytesIO()
newimg.thumbnail(size)
newimg.save(output_io,format='WEBP')
newimg.close()
output_io.seek(0)
return output_io
def thumbnail(input, minSize: int = 600):
img = cv2.imdecode(np.frombuffer(input, np.uint8), cv2.IMREAD_COLOR)
height = img.shape[0] # 图片高度
width = img.shape[1] # 图片宽度
if height < width:
newshape = (int(minSize / width * height), minSize)
else:
newshape = (minSize, int(minSize / width * height))
img = cv2.resize(img, newshape)
success, encoded_image = cv2.imencode(".webp", img, [cv2.IMWRITE_WEBP_QUALITY, 75])
return encoded_image.tobytes()

View File

@ -1,3 +1,3 @@
shortuuid
flask
Pillow
opencv-python

View File

@ -18,7 +18,7 @@ def img(bookid, index): # 图片接口
if request.args.get("mini") == "yes":
data = file.thumbnail(data)
else:
data = file.imageToWebP(data)
data = file.thumbnail(data,2400)
response = make_response(data) # 读取文件
del data
response.headers.set("Content-Type", "image/Webp")