Esempio n. 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
Esempio n. 2
0
    def _get_image_tag(self, match, path=None, format="png"):
        """ Return (X)HTML mark-up for the image-tag given by match.

        Parameters
        ----------
        match : re.SRE_Match
            A match to an HTML image tag as exported by Qt, with
            match.group("Name") containing the matched image ID.

        path : string|None, optional [default None]
            If not None, specifies a path to which supporting files may be
            written (e.g., for linked images).  If None, all images are to be
            included inline.

        format : "png"|"svg"|"jpg", optional [default "png"]
            Format for returned or referenced images.
        """
        if format in ("png", "jpg"):
            try:
                image = self._get_image(match.group("name"))
            except KeyError:
                return "<b>Couldn't find image %s</b>" % match.group("name")

            if path is not None:
                ensure_dir_exists(path)
                relpath = os.path.basename(path)
                if image.save(
                        "%s/qt_img%s.%s" % (path, match.group("name"), format),
                        "PNG"):
                    return '<img src="%s/qt_img%s.%s">' % (
                        relpath, match.group("name"), format)
                else:
                    return "<b>Couldn't save image!</b>"
            else:
                ba = QtCore.QByteArray()
                buffer_ = QtCore.QBuffer(ba)
                buffer_.open(QtCore.QIODevice.WriteOnly)
                image.save(buffer_, format.upper())
                buffer_.close()
                return '<img src="data:image/%s;base64,\n%s\n" />' % (
                    format,
                    re.sub(r'(.{60})', r'\1\n',
                           str(ba.toBase64().data().decode())))

        elif format == "svg":
            try:
                svg = str(self._name_to_svg_map[match.group("name")])
            except KeyError:
                if not self._svg_warning_displayed:
                    QtGui.QMessageBox.warning(
                        self, 'Error converting PNG to SVG.',
                        'Cannot convert PNG images to SVG, export with PNG figures instead. '
                        'If you want to export matplotlib figures as SVG, add '
                        'to your ipython config:\n\n'
                        '\tc.InlineBackend.figure_format = \'svg\'\n\n'
                        'And regenerate the figures.', QtGui.QMessageBox.Ok)
                    self._svg_warning_displayed = True
                return (
                    "<b>Cannot convert  PNG images to SVG.</b>  "
                    "You must export this session with PNG images. "
                    "If you want to export matplotlib figures as SVG, add to your config "
                    "<span>c.InlineBackend.figure_format = 'svg'</span> "
                    "and regenerate the figures.")

            # Not currently checking path, because it's tricky to find a
            # cross-browser way to embed external SVG images (e.g., via
            # object or embed tags).

            # Chop stand-alone header from matplotlib SVG
            offset = svg.find("<svg")
            assert (offset > -1)

            return svg[offset:]

        else:
            return '<b>Unrecognized image format</b>'