|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import base64 |
|
|
import mimetypes |
|
|
import logging |
|
|
|
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
|
|
def image_to_base64_data_url(image_path): |
|
|
"""Reads an image file, encodes it to base64, and returns a data URL.""" |
|
|
try: |
|
|
mime_type, _ = mimetypes.guess_type(image_path) |
|
|
if not mime_type: |
|
|
|
|
|
mime_type = "image/jpeg" |
|
|
logger.warning(f"Could not determine MIME type for {image_path}, defaulting to {mime_type}") |
|
|
|
|
|
with open(image_path, "rb") as image_file: |
|
|
encoded_string = base64.b64encode(image_file.read()).decode('utf-8') |
|
|
return f"data:{mime_type};base64,{encoded_string}" |
|
|
except FileNotFoundError: |
|
|
logger.error(f"Image file not found at {image_path} for base64 encoding.") |
|
|
return None |
|
|
except Exception as e: |
|
|
logger.error(f"Error encoding image to base64: {e}", exc_info=True) |
|
|
return None |