svg2png / app.py
codelion's picture
Update app.py
8e6acfa verified
raw
history blame
2.18 kB
import cairosvg
import gradio as gr
from PIL import Image
import os
import xml.etree.ElementTree as ET
def show(svg_file):
# Check if no file is uploaded
if svg_file is None:
return None, None
# Read the SVG content
with open(svg_file.name, 'rb') as f:
svg_content = f.read()
# Parse SVG to extract width and height
try:
root = ET.fromstring(svg_content)
width = root.get('width')
height = root.get('height')
if width and height:
# Remove units (like 'px') and convert to float
width = float(''.join(filter(str.isdigit, width)) or width)
height = float(''.join(filter(str.isdigit, height)) or height)
else:
width = height = None
except ET.ParseError:
# Handle invalid SVG
width = height = None
# Define output path
output_path = "./test.png"
# Convert SVG to PNG with explicit size if available
if width and height:
cairosvg.svg2png(
bytestring=svg_content,
write_to=output_path,
output_width=width,
output_height=height
)
else:
# Fallback to default rendering with a reasonable size
cairosvg.svg2png(
bytestring=svg_content,
write_to=output_path,
output_width=1600, # Default width if not specified
output_height=1200 # Default height if not specified
)
# Load the PNG as a PIL image
png_image = Image.open(output_path)
return png_image, output_path
with gr.Blocks() as bl:
gr.Markdown("# SVG to PNG Converter")
with gr.Row():
with gr.Column():
svg_input = gr.File(label="Upload SVG File", file_types=[".svg"])
convert_btn = gr.Button("Convert")
with gr.Column():
png_output = gr.Image(type='pil', label="Converted PNG", height=800)
download_btn = gr.File(label="Download PNG")
# Connect the conversion function
convert_btn.click(
fn=show,
inputs=svg_input,
outputs=[png_output, download_btn]
)
bl.launch()