Exemple #1
0
def svg_to_image(string, size=None):
    """ Convert a SVG document to a QImage.

    Parameters
    ----------
    string : basestring
        A Python string containing a SVG document.

    size : QSize, optional
        The size of the image that is produced. If not specified, the SVG
        document's default size is used.
    
    Raises
    ------
    ValueError
        If an invalid SVG string is provided.

    Returns
    -------
    A QImage of format QImage.Format_ARGB32.
    """
    if isinstance(string, unicode_type):
        string = string.encode('utf-8')

    renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
    if not renderer.isValid():
        raise ValueError('Invalid SVG data.')

    if size is None:
        size = renderer.defaultSize()
    image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
    painter = QtGui.QPainter(image)
    renderer.render(painter)
    return image
 def _insert_img(self, cursor, img, fmt, metadata=None):
     """ insert a raw image, jpg or png """
     if metadata:
         width = metadata.get('width', None)
         height = metadata.get('height', None)
     else:
         width = height = None
     try:
         image = QtGui.QImage()
         image.loadFromData(img, fmt.upper())
         if width and height:
             image = image.scaled(
                 width,
                 height,
                 transformMode=QtCore.Qt.SmoothTransformation)
         elif width and not height:
             image = image.scaledToWidth(
                 width, transformMode=QtCore.Qt.SmoothTransformation)
         elif height and not width:
             image = image.scaledToHeight(
                 height, transformMode=QtCore.Qt.SmoothTransformation)
     except ValueError:
         self._insert_plain_text(cursor, 'Received invalid %s data.' % fmt)
     else:
         format = self._add_image(image)
         cursor.insertBlock()
         cursor.insertImage(format)
         cursor.insertBlock()