File size: 1,314 Bytes
4a121a0
a8aa56e
4a121a0
a6a908a
ee6a1c6
1b43408
 
 
4a121a0
1b43408
 
 
4a121a0
 
 
 
 
 
 
 
 
 
 
 
 
 
a8aa56e
4a121a0
 
a8aa56e
4a121a0
 
 
 
 
 
 
 
 
 
 
a8aa56e
4a121a0
 
 
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
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