tuon 1 жил өмнө
parent
commit
f0acbf4f8b
2 өөрчлөгдсөн 42 нэмэгдсэн , 7 устгасан
  1. 23 0
      api/file.py
  2. 19 7
      api/image.py

+ 23 - 0
api/file.py

@@ -88,5 +88,28 @@ def get_output_file_path(filename: str, suffix: str = None, fun: str = None):
     return os.path.join(OUTPUT_DIR, filename)
 
 
+def get_file_id(path, output=False):
+    if output:
+        file_id = os.path.relpath(path, OUTPUT_DIR)
+        return "o_{}".format(file_id)
+    file_id = os.path.relpath(path, UPLOAD_PATH)
+    return file_id
+
+
+def get_file_id_path(filename: str):
+    # 根据文件名称,获取文件的路径
+    if str is None or len(filename) == 0:
+        return None
+    if filename.startswith("o_"):
+        real_name = filename[2:]
+        path = os.path.join(OUTPUT_DIR, real_name)
+        if os.path.exists(path):
+            return path
+    path = os.path.join(UPLOAD_PATH, filename)
+    if os.path.exists(path):
+        return path
+    return None
+
+
 def get_upload_file_path(name):
     return os.path.join(UPLOAD_PATH, name)

+ 19 - 7
api/image.py

@@ -1,13 +1,12 @@
 import os
 from flask import request, logging, send_file, jsonify
-from werkzeug.datastructures import CombinedMultiDict
 from app import app
 from .resp import success_resp, error_resp
 import numpy as np
 from .req import ReplaceForm, is_empty
 import tools
 import cv2
-from .file import get_upload_file_path, get_output_dir, file_url, get_output_file_path
+from .file import get_upload_file_path, get_output_dir, file_url, get_output_file_path, get_file_id
 
 log = logging.create_logger(app)
 
@@ -48,7 +47,7 @@ def replace():
     result = tools.replace(img_path=img_path, background=bg_path, save_dir=get_output_dir())
 
     return jsonify({
-        "fileId": form.file_id.data,
+        "fileId": get_file_id(result, True),
         "url": file_url(result, True)
     })
 
@@ -74,8 +73,10 @@ def resize():
 
     file_path = get_upload_file_path(file_id)
 
+    is_get = request.method.upper() == "GET"
+
     if os.path.exists(file_path) is not True:
-        return "文件上传失败,请重新上传!", 400
+        return "文件上传失败,请重新上传!" if is_get else jsonify(error_resp("文件上传失败,请重新上传")), 400
 
     out_file = get_output_file_path(file_id, "resize")
     if reset is False and os.path.exists(out_file):
@@ -116,9 +117,20 @@ def resize():
 
     if dst is not None:
         cv2.imwrite(out_file, dst)
-        return send_file(out_file, mimetype="image/png")
-
-    return send_file(file_path, mimetype="image/png")
+        if is_get:
+            return send_file(out_file, mimetype="image/png")
+        else:
+            return jsonify(success_resp({
+                "fileId": get_file_id(out_file),
+                "url": file_url(out_file)
+            }))
+
+    if is_get:
+        return send_file(file_path, mimetype="image/png")
+    return jsonify(success_resp({
+        "fileId": get_file_id(file_path),
+        "url": file_url(file_path)
+    }))
 
 
 def crop(img, rect: str, w, h):