posted on: 2009-02-27 06:27:05
I found that PyQt4 Svg rendering is very nice so I felt I should post a snippet of the code.

>I was making animations with a Graphics view and some svg images, when I noticed that my other application being used to produce .png files produced poor quality bitmaps, but Qt makes them look realy nice, so I wrote a short program that writes the files to a bit.

#!/usr/bin/env python

"""
A short program to convert svg files to png files
"""
from PyQt4 import QtGui,QtCore,QtSvg

import sys

class MyView(QtGui.QGraphicsView):
    """
        Uses a graphics view to render an svg image.
    """
    def __init__(self,f):
        QtGui.QGraphicsView.__init__(self)
        
        item = QtSvg.QGraphicsSvgItem(f)
        self.scene = QtGui.QGraphicsScene(self)
        item.setPos(QtCore.QPointF(0,0))
        self.scene.addItem(item)

        self.setScene(self.scene)
        
        self.saveImage(f)
                
    def saveImage(self,f):
        """
            create a QImage and render graphics scene to it.
        """
        isize = self.scene.sceneRect().size().toSize()
        self.qimage = QtGui.QImage(isize,QtGui.QImage.Format_ARGB32)
        painter = QtGui.QPainter(self.qimage)
        self.scene.render(painter)    
        self.qimage.save(f.replace('.svg','.png'))
        
if __name__=="__main__":
    if len(sys.argv)>1:
        app = QtGui.QApplication(sys.argv)
        db = MyView(sys.argv[1])
        db.show()
        sys.exit(app.exec_())
    else:
        print "useage: svg_to_png.py my_file.svg"
        print "will produce my_file.png"

The beauty is I use it and it works great. There are some problems with text, but the graphics rendering looks very good. And if you are going to use animations, this is halfway there.

Here it is as a file

svg_to_png.py

Comments

Name: