diff --git a/file.py b/file.py index 4dcd617..e478490 100644 --- a/file.py +++ b/file.py @@ -1,11 +1,12 @@ -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") + paths = ("inputdir", "storedir", "tmpdir") for path in paths: try: os.makedirs(app_conf.get("file", path)) @@ -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() diff --git a/requirements.txt b/requirements.txt index 1f8ad7c..b7a17c1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ shortuuid flask -Pillow \ No newline at end of file +opencv-python \ No newline at end of file diff --git a/web/api_Img.py b/web/api_Img.py index dfc0cdc..4830b0e 100644 --- a/web/api_Img.py +++ b/web/api_Img.py @@ -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")