[pygame] Modifying SVG image

127 views
Skip to first unread message

Go Peppy

unread,
Apr 11, 2022, 1:03:11 PM4/11/22
to pygame...@seul.org
Hi,

The following command works fine in Pygame 2:
pygame.image.load("test.svg")
It loads an SVG file and creates a Surface object.

I need to change colors in that SVG image/file. As this is a text file this is a pretty simple task.
The only way I see is to load an SVG file, change colors, save file and then load using pygame.image.load. Is it possible to accomplish that task without creating/saving a new SVG file?

Thanks in advance!

Jim

unread,
Apr 21, 2022, 2:45:11 PM4/21/22
to pygame...@seul.org
I don't know the answer to your question but if you are concerned with
the delay in reading/modifying/writing/reading you can speed that up by
using a RAM disk.

Jim

Go Peppy

unread,
Apr 21, 2022, 4:25:15 PM4/21/22
to pygame...@seul.org
Hi Jim,

Yes, I'm using a memory mapped file to avoid saving any intermediate file. Here is the pseudo-code which reads the SVG file and replaces all occurrences of one color (#C0C0C0) by another (#000000). String encoding is required as a memory mapped file is the byte array. There is one limitation in this approach - the size of the object which you replace should be of the same size as the object by which you replace. It was not the problem in this particular case though.

import mmap
import contextlib

bitmap_image = None
with open("test.svg", "r") as f:
    with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY)) as m:
        old_color = "#C0C0C0".encode()
        pos = m.find(old_color)
        new_color = "#000000"
        while pos != -1:
            m[pos : pos + len(new_color)] = new_color.encode()
            pos = m.find(old_color)
        bitmap_image = pygame.image.load(m).convert_alpha()

Best regards
Reply all
Reply to author
Forward
0 new messages