pythonsvgsvgwrite

How to insert image into a circle element of svg? (Python: svgwrite)


I know how to do this task on a normal SVG file but I'm using svgwrite package in python 3.7 and I don't know how to do this. Sadly website documentation doesn't cover this topic accurately enough...

Here is the code I came up with and it won't work:

image.add(image.ellipse(center=(half_x, half_y), r=(340, 340), fill=line_color, cx=50, cy=50, rx=80, ry=60, stroke="rgb(255,255,255)", opacity=0.3, stroke_width="0.5", id="img-container"))
image.add(image.image(href="https://images.pexels.com/photos/799443/pexels-photo-799443.jpeg", insert=None, size=("100%","100%"), clip_path="img-container"))

I just want to have a circle image in my SVG file. if you know any better approach please let me know!

edit: Also when I want to use clipPath i got below error:

ValueError: Invalid children 'image' for svg-element <clipPath>.

Solution

  • I used mask to do this task. first, add a mask element with an id of wrapper then add a circle element as a child of the mask. the final trick is to add mask property to the image element like url(#bg_wrapper).

    code solution:

    image = svgwrite.Drawing(output_file, size=(str(width)+'mm', str(height)+'mm'))
    
    # Custom image
    mask = image.defs.add(image.mask(id="bg_wrapper"))
    mask.add(image.circle(center=(half_x, half_y), r=335, fill=line_color, opacity=".4"))
    image.add(image.image(href="image.jpeg", size=("100%", "100%"), mask="url(#bg_wrapper)"))