From 007645e94d47e6888c43579ebaa1668aaafd5490 Mon Sep 17 00:00:00 2001 From: Kakune55 Date: Thu, 9 May 2024 11:26:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E5=B0=86=E5=9B=BE=E5=83=8F=E5=A4=84?= =?UTF-8?q?=E7=90=86=E5=BA=93=E4=BB=8EPIL=E6=94=B9=E4=B8=BAOpenCV=E4=BB=A5?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- file.py | 42 +++++++++++++++--------------------------- requirements.txt | 2 +- web/api_Img.py | 2 +- 3 files changed, 17 insertions(+), 29 deletions(-) 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")