File size: 1,888 Bytes
4a121a0 a8aa56e 4a121a0 a6a908a ee6a1c6 1b43408 4a121a0 1b43408 4a121a0 a8aa56e 4a121a0 a8aa56e 4a121a0 a8aa56e 4a121a0 07efcb2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import xml.etree.ElementTree as ET
from PIL import Image
import cairosvg
def show(svg_file):
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 'px' units and convert to float
width = float(width.replace('px', ''))
height = float(height.replace('px', ''))
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 if no size is specified
cairosvg.svg2png(bytestring=svg_content, write_to=output_path)
# 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")
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() |