import re from PIL import Image import io import os TEST_PHOTOS_FOLDER = "/mnt/c/Users/KMult/Desktop/Praca_inzynierska/zdjecia_testowe/" TEST_RESULTS_FOLDER = "./results" def return_image_response(image: Image.Image): from fastapi.responses import StreamingResponse buffer = io.BytesIO() image.save(buffer, format="PNG") buffer.seek(0) return StreamingResponse(buffer, media_type="image/png") def open_image(file_path: str) -> Image.Image: image_path = os.path.join(TEST_PHOTOS_FOLDER, file_path) if not os.path.exists(image_path): raise FileNotFoundError(f"File not found: {image_path}") try: img = Image.open(image_path) img.load() return img except OSError as e: raise OSError(f"Could not open file as image: {image_path}") from e def get_next_result_number(folder_path: str): if not os.path.exists(folder_path): return 1 numbers = [] for filename in os.listdir(folder_path): match = re.match(r"result(\d+)\.png", filename) if match: numbers.append(int(match.group(1))) return max(numbers, default=0) + 1 def save_result_file(image: Image.Image): os.makedirs(TEST_RESULTS_FOLDER, exist_ok=True) next_number = get_next_result_number(TEST_RESULTS_FOLDER) output_path = os.path.join(TEST_RESULTS_FOLDER, f"result{next_number}.png") buffer = io.BytesIO() image.save(buffer, format="PNG") buffer.seek(0) with open(output_path, "wb") as f: f.write(buffer.read()) print(f"Image saved to {output_path}")