Home > Enterprise >  Filling color in svg image
Filling color in svg image

Time:07-18

I have an svg file in this format:

<svg xmlns="http://www.w3.org/2000/svg" height="48" width="48">
  <path d="M11.45 43.25Q9.5 43.25 8.125 41.875Q6.75 40.5 6.75 38.55V19.7Q6.75 18.6 7.25 17.6Q7.75 16.6 8.65 15.95L21.15 6.55Q21.8 6.1 22.55 5.85Q23.3 5.6 24 5.6Q24.75 5.6 25.475 5.85Q26.2 6.1 26.85 6.55L39.35 15.95Q40.25 16.65 40.775 17.625Q41.3 18.6 41.3 19.7V38.55Q41.3 40.5 39.9 41.875Q38.5 43.25 36.55 43.25H28.3V27.7H19.7V43.25Z"/>
</svg>

This vector image looks like this:
an svg image of a "home" icon

(saved at specified location, say 'path/to/file.svg')

The svg should be filled with solid color of specified hex code (in place of all the black color)

Example: I want the 'svg42.svg' to be filled with solid color '#00bbaa'

What I tried:

Here is a snippet from the code I tried:

import io
import tksvg
from lxml import etree
root = etree.fromstring(source)
tree = etree.ElementTree(root)

# set path fill color if provided
if fill is not None:
    root.attrib["fill"] = fill

imgdata = io.BytesIO()
tree.write(imgdata)
kw = {"data": imgdata.getvalue()}
if scale != 1:
    kw["scale"] = scale

return tksvg.SvgImage(**kw)

source is the svg data, fill is the hex color, and there is also another parameter - scale

How can this be done in minimal steps?

CodePudding user response:

import io

from PIL import Image
from cairosvg import svg2png
from lxml import etree


def svg2image(file: str, color: str, width: int, height: int):
    with open(f'{file}', 'r') as f:
        svg_data = f.read()

    root = etree.fromstring(svg_data)
    tree = etree.ElementTree(root)
    root.attrib["fill"] = color
    imgdata = io.BytesIO()
    tree.write(imgdata)

    img = svg2png(bytestring=imgdata.getvalue(), output_width=width, output_height=height)
    img = Image.open(io.BytesIO(img))

    return img
  • Related