Spaces:
Running
Running
feat: add svg_to_png_base64 function for converting SVG to base64 encoded PNG
Browse files
utils.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
import cairosvg
|
| 5 |
+
import io
|
| 6 |
+
import base64
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def svg_to_png_base64(svg_content: str, width=800, height=800) -> tuple[str, str]:
|
| 11 |
+
"""Convert SVG to PNG and return as base64 encoded string with media type.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
svg_content: SVG markup string
|
| 15 |
+
width: Desired PNG width
|
| 16 |
+
height: Desired PNG height
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
Tuple of (media_type, base64_string)
|
| 20 |
+
"""
|
| 21 |
+
try:
|
| 22 |
+
# Convert SVG to PNG using cairosvg
|
| 23 |
+
png_data = cairosvg.svg2png(
|
| 24 |
+
bytestring=svg_content.encode("utf-8"),
|
| 25 |
+
output_width=width,
|
| 26 |
+
output_height=height,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Open PNG with Pillow to ensure correct format
|
| 30 |
+
img = Image.open(io.BytesIO(png_data))
|
| 31 |
+
|
| 32 |
+
# Convert to RGB if needed
|
| 33 |
+
if img.mode != "RGB":
|
| 34 |
+
img = img.convert("RGB")
|
| 35 |
+
|
| 36 |
+
# Save as PNG to bytes
|
| 37 |
+
img_byte_arr = io.BytesIO()
|
| 38 |
+
img.save(img_byte_arr, format="PNG")
|
| 39 |
+
img_byte_arr = img_byte_arr.getvalue()
|
| 40 |
+
|
| 41 |
+
# Encode to base64
|
| 42 |
+
base64_str = base64.b64encode(img_byte_arr).decode("utf-8")
|
| 43 |
+
|
| 44 |
+
return "image/png", base64_str
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Error converting SVG to PNG: {e}")
|
| 48 |
+
return "", ""
|