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:
- 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 (????).
- I tried to reinitialize the base svg in every cycle of the inner loop.
- 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