codelion commited on
Commit
4a121a0
·
verified ·
1 Parent(s): 1b43408

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -32
app.py CHANGED
@@ -1,44 +1,45 @@
1
- import cairosvg
2
- import gradio as gr
3
  from PIL import Image
4
- import os
5
- from io import BytesIO
6
 
7
  def show(svg_file):
8
- # Check if svg_file is None (no file uploaded)
9
  if svg_file is None:
10
  return None, None
11
 
12
- # Get the file content from the Gradio file object
13
- # svg_file is a tempfile._TemporaryFileWrapper or similar object
14
  with open(svg_file.name, 'rb') as f:
15
  svg_content = f.read()
16
 
17
- # Convert SVG content to PNG
18
- output_path = "./test.png"
19
- cairosvg.svg2png(bytestring=svg_content, write_to=output_path)
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- # Open and return the PNG image
22
- png_image = Image.open(output_path)
23
- return png_image, output_path
24
-
25
- with gr.Blocks() as bl:
26
- gr.Markdown("# SVG to PNG Converter")
27
 
28
- with gr.Row():
29
- with gr.Column():
30
- svg_input = gr.File(label="Upload SVG File", file_types=[".svg"])
31
- convert_btn = gr.Button("Convert")
32
-
33
- with gr.Column():
34
- png_output = gr.Image(type='pil', label="Converted PNG")
35
- download_btn = gr.File(label="Download PNG")
 
 
 
36
 
37
- # Connect the conversion function
38
- convert_btn.click(
39
- fn=show,
40
- inputs=svg_input,
41
- outputs=[png_output, download_btn]
42
- )
43
-
44
- bl.launch()
 
1
+ import xml.etree.ElementTree as ET
 
2
  from PIL import Image
3
+ import cairosvg
 
4
 
5
  def show(svg_file):
 
6
  if svg_file is None:
7
  return None, None
8
 
9
+ # Read the SVG content
 
10
  with open(svg_file.name, 'rb') as f:
11
  svg_content = f.read()
12
 
13
+ # Parse SVG to extract width and height
14
+ try:
15
+ root = ET.fromstring(svg_content)
16
+ width = root.get('width')
17
+ height = root.get('height')
18
+ if width and height:
19
+ # Remove 'px' units and convert to float
20
+ width = float(width.replace('px', ''))
21
+ height = float(height.replace('px', ''))
22
+ else:
23
+ width = height = None
24
+ except ET.ParseError:
25
+ # Handle invalid SVG
26
+ width = height = None
27
 
28
+ # Define output path
29
+ output_path = "./test.png"
 
 
 
 
30
 
31
+ # Convert SVG to PNG with explicit size if available
32
+ if width and height:
33
+ cairosvg.svg2png(
34
+ bytestring=svg_content,
35
+ write_to=output_path,
36
+ output_width=width,
37
+ output_height=height
38
+ )
39
+ else:
40
+ # Fallback to default rendering if no size is specified
41
+ cairosvg.svg2png(bytestring=svg_content, write_to=output_path)
42
 
43
+ # Load the PNG as a PIL image
44
+ png_image = Image.open(output_path)
45
+ return png_image, output_path