Spaces:
Running
Running
| import base64 | |
| from fastapi import UploadFile | |
| from src.services.google_cloud_image_upload import GoogleCloudImageUploadService | |
| from PIL import Image | |
| from urllib.request import urlopen | |
| import io | |
| def image_path_to_base64(image_path: str) -> str: | |
| with open(image_path, "rb") as image_file: | |
| return base64.b64encode(image_file.read()).decode("utf-8") | |
| def upload_file_to_base64(file: UploadFile) -> str: | |
| return base64.b64encode(file.file.read()).decode("utf-8") | |
| def image_path_to_uri(image_path: str) -> str: | |
| return f"data:image/jpeg;base64,{image_path_to_base64(image_path)}" | |
| def upload_image(image_path: str) -> str: | |
| """ | |
| Upload an image to Google Cloud Storage and return the public URL. | |
| Args: | |
| image (str): The path to the image file. | |
| Returns: | |
| str: The public URL of the uploaded image. | |
| """ | |
| upload_service = GoogleCloudImageUploadService() | |
| return upload_service.upload_image_to_gcs(image_path) | |
| def download_image_to_data_uri(image_url: str) -> str: | |
| # Open the image from the URL | |
| response = urlopen(image_url) | |
| img = Image.open(response) | |
| # Determine the image format; default to 'JPEG' if not found | |
| image_format = img.format if img.format is not None else "JPEG" | |
| # Build the MIME type; for 'JPEG', use 'image/jpeg' | |
| mime_type = ( | |
| "image/jpeg" | |
| if image_format.upper() == "JPEG" | |
| else f"image/{image_format.lower()}" | |
| ) | |
| # Save the image to an in-memory buffer using the detected format | |
| buffered = io.BytesIO() | |
| img.save(buffered, format=image_format) | |
| # Encode the image bytes to base64 | |
| img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8") | |
| # Return the data URI with the correct MIME type | |
| return f"data:{mime_type};base64,{img_base64}" | |