|
1 | 1 | import os |
2 | 2 | import sys |
3 | 3 | import base64 |
4 | | -import tempfile |
5 | 4 | import urllib.request |
6 | 5 |
|
7 | 6 | import cv2 |
@@ -186,14 +185,14 @@ def handler(job): |
186 | 185 | model_name = "x4plus" |
187 | 186 |
|
188 | 187 | # Process input image |
189 | | - tmp_dir = tempfile.mkdtemp() |
190 | | - input_path = os.path.join(tmp_dir, "input_img.png") |
| 188 | + img = None |
191 | 189 |
|
192 | 190 | if isinstance(image_source, str) and (image_source.startswith("http://") or image_source.startswith("https://")): |
193 | 191 | print(f"📥 [Web Fetch] Downloading image from URL: {image_source}") |
194 | 192 | try: |
195 | | - urllib.request.urlretrieve(image_source, input_path) |
196 | | - img = cv2.imread(input_path, cv2.IMREAD_COLOR) |
| 193 | + with urllib.request.urlopen(image_source) as response: |
| 194 | + img_array = np.frombuffer(response.read(), np.uint8) |
| 195 | + img = cv2.imdecode(img_array, cv2.IMREAD_COLOR) |
197 | 196 | except Exception as e: |
198 | 197 | return {"error": f"Failed to download image from URL: {str(e)}"} |
199 | 198 | elif isinstance(image_source, str) and os.path.exists(image_source): |
@@ -236,11 +235,12 @@ def handler(job): |
236 | 235 | else: |
237 | 236 | output, _ = upsampler.enhance(img, outscale=s) |
238 | 237 |
|
239 | | - out_path = os.path.join(tmp_dir, "output.jpg") |
240 | | - cv2.imwrite(out_path, output, [cv2.IMWRITE_JPEG_QUALITY, 95]) |
241 | | - |
242 | | - with open(out_path, "rb") as f: |
243 | | - b64 = base64.b64encode(f.read()).decode("utf-8") |
| 238 | + # Encode output directly to Base64 in-memory |
| 239 | + success, encoded_img = cv2.imencode(".jpg", output, [cv2.IMWRITE_JPEG_QUALITY, 95]) |
| 240 | + if not success: |
| 241 | + return {"error": "Failed to encode output image"} |
| 242 | + |
| 243 | + b64 = base64.b64encode(encoded_img).decode("utf-8") |
244 | 244 |
|
245 | 245 | h, w = img.shape[:2] |
246 | 246 | oh, ow = output.shape[:2] |
|
0 commit comments