Spaces:
Sleeping
Sleeping
| import base64 | |
| import cairosvg | |
| import io | |
| import base64 | |
| from PIL import Image | |
| def svg_to_png_base64(svg_content: str, width=800, height=800) -> tuple[str, str]: | |
| """Convert SVG to PNG and return as base64 encoded string with media type. | |
| Args: | |
| svg_content: SVG markup string | |
| width: Desired PNG width | |
| height: Desired PNG height | |
| Returns: | |
| Tuple of (media_type, base64_string) | |
| """ | |
| try: | |
| # Convert SVG to PNG using cairosvg | |
| png_data = cairosvg.svg2png( | |
| bytestring=svg_content.encode("utf-8"), | |
| output_width=width, | |
| output_height=height, | |
| ) | |
| # Open PNG with Pillow to ensure correct format | |
| img = Image.open(io.BytesIO(png_data)) | |
| # Convert to RGB if needed | |
| if img.mode != "RGB": | |
| img = img.convert("RGB") | |
| # Save as PNG to bytes | |
| img_byte_arr = io.BytesIO() | |
| img.save(img_byte_arr, format="PNG") | |
| img_byte_arr = img_byte_arr.getvalue() | |
| # Encode to base64 | |
| base64_str = base64.b64encode(img_byte_arr).decode("utf-8") | |
| return "image/png", base64_str | |
| except Exception as e: | |
| print(f"Error converting SVG to PNG: {e}") | |
| return "", "" | |