简体   繁体   中英

Create pixbuf in PyGtk3 from svg as string

Let's say I read a svg file in memory. After manipulating the string (changing colours, gradients etc.) I wan't to include the (now modified) svg "file" in a graphical user interface written using PyGTK3. The easiest way to do this is to save the svg again as a file and to something like

Gtk.Image.new_from_file(modified_svg)

Since I wan't to do this a lot there's a lot of unnecessary data writing/reading from the slow harddisk. Is there a way to directly create the Image from the svg-string in the memory? (I thought about something similar to a pixbuf but I wasn't able to find something)

You have to use a GdkPixbuf.PixbufLoader ( documentation ). This is what it looks like:

#!/usr/bin/env python3
from gi.repository import Gtk, WebKit, GLib, GdkPixbuf

svg = """
 <svg width="350" height="110">
   <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
   </svg> 
"""

class Window(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.connect('delete-event', Gtk.main_quit)

        loader = GdkPixbuf.PixbufLoader()
        loader.write(svg.encode())
        loader.close()
        pixbuf = loader.get_pixbuf()
        image = Gtk.Image.new_from_pixbuf(pixbuf)

        self.add(image)
        self.show_all()


if __name__ == "__main__":
    Window()
    Gtk.main()

If you already have a Gtk.Image and you just want to update it, you can use Gtk.Image.set_from_pixbuf() instead of Gtk.Image.new_from_pixbuf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM