0

I'm trying to stack different svg images as layers onto a base svg which is empty using python 3.9 and svgutils and svgwrite methods. The code gets all the svgs from one directory and images filenames are formatted as "n_x.svg" where n and x are variables; I should stack them following a path defined into this list:

unique_comb = random.sample(result, 100)
print(list(unique_comb[0]))

>>>['1_2', '2_3', '3_1', '4_1', '5_1', '6_2', '7_6']

This is a sample from a 100 unique combinations list. Here the iteration that stacks the svgs:

import svgwrite
import svgutils.transform as st

if __name__ == "__main__":

# PATH to svgs directory
os.chdir(PATH)

for i in range(0, 100):
    
    template = st.SVGFigure("400px", "400px")

    for j in range(0, len(unique_comb[i])):

        rand = unique_comb[i][j]
        layer_x = st.fromfile(f"{rand}.svg")
        template.append(layer_x)

    template.save(f"Image{i+1}.svg")

The problem is the following: append method is not working properly as it stacks 1 or 2 images correctly then it stacks random svgs from the source directory. I tried to debug it in some ways:

  1. I tried to limit the iteration adding one image at a time and it gave as a output a strange combination of all the 7 svgs layers after stacking just 3 images (????).
  2. I tried to reinitialize the base svg in every cycle of the inner loop.
  3. I've stacked images without iterating and defining "manually" each layer (layer_1 =st.fromfile(f"{rand[0]}.svg"); layer_2 = st.fromfile(f"{rand[1]}.svg"); .....) and then appending them one by one.

It seems like append gets confused about which image it should stack and creates a messy result.

Which other way should I try to debug this method? Is there any other way to stack svgs iteratively?

Thank you so much

oilCPL
  • 1
  • first you could use `print()` to see which part of code is executed and what you have in variables. – furas Mar 14 '22 at 23:08
  • I tried to print almost everything in my code and it seems to have the correct behavior in each part. I have looked for similar questions and it could be a problem related to css classes in svgs' xmls, and how append method use them. Are there alternatives with respect to append method or even to svgs images to get the result I expect? – oilCPL Mar 15 '22 at 06:44

0 Answers0