Python matplotlib._png.write_png() Examples

The following are 30 code examples of matplotlib._png.write_png(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib._png , or try the search function .
Example #1
Source File: backend_agg.py    From ImageFusion with MIT License 6 votes vote down vote up
def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()
        original_dpi = renderer.dpi
        renderer.dpi = self.figure.dpi
        if is_string_like(filename_or_obj):
            filename_or_obj = open(filename_or_obj, 'wb')
            close = True
        else:
            close = False
        try:
            _png.write_png(renderer._renderer.buffer_rgba(),
                           renderer.width, renderer.height,
                           filename_or_obj, self.figure.dpi)
        finally:
            if close:
                filename_or_obj.close()
        renderer.dpi = original_dpi 
Example #2
Source File: backend_pgf.py    From neural-network-animation with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # TODO: Almost no documentation for the behavior of this function.
        #       Something missing?

        # save the images to png files
        path = os.path.dirname(self.fh.name)
        fname = os.path.splitext(os.path.basename(self.fh.name))[0]
        fname_img = "%s-img%d.png" % (fname, self.image_counter)
        self.image_counter += 1
        im.flipud_out()
        rows, cols, buf = im.as_rgba_str()
        _png.write_png(buf, cols, rows, os.path.join(path, fname_img))

        # reference the image in the pgf picture
        writeln(self.fh, r"\begin{pgfscope}")
        self._print_pgf_clip(gc)
        h, w = im.get_size_out()
        f = 1. / self.dpi  # from display coords to inch
        writeln(self.fh, r"\pgftext[at=\pgfqpoint{%fin}{%fin},left,bottom]{\pgfimage[interpolate=true,width=%fin,height=%fin]{%s}}" % (x * f, y * f, w * f, h * f, fname_img))
        writeln(self.fh, r"\end{pgfscope}") 
Example #3
Source File: backend_agg.py    From neural-network-animation with MIT License 6 votes vote down vote up
def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()
        original_dpi = renderer.dpi
        renderer.dpi = self.figure.dpi
        if is_string_like(filename_or_obj):
            filename_or_obj = open(filename_or_obj, 'wb')
            close = True
        else:
            close = False
        try:
            _png.write_png(renderer._renderer.buffer_rgba(),
                           renderer.width, renderer.height,
                           filename_or_obj, self.figure.dpi)
        finally:
            if close:
                filename_or_obj.close()
        renderer.dpi = original_dpi 
Example #4
Source File: backend_pdf.py    From CogAlg with MIT License 6 votes vote down vote up
def _writePng(self, data):
        """
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        """
        buffer = BytesIO()
        _png.write_png(data, buffer)
        buffer.seek(8)
        while True:
            length, type = struct.unpack(b'!L4s', buffer.read(8))
            if type == b'IDAT':
                data = buffer.read(length)
                if len(data) != length:
                    raise RuntimeError("truncated data")
                self.currentstream.write(data)
            elif type == b'IEND':
                break
            else:
                buffer.seek(length, 1)
            buffer.seek(4, 1)   # skip CRC 
Example #5
Source File: backend_pgf.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # TODO: Almost no documentation for the behavior of this function.
        #       Something missing?

        # save the images to png files
        path = os.path.dirname(self.fh.name)
        fname = os.path.splitext(os.path.basename(self.fh.name))[0]
        fname_img = "%s-img%d.png" % (fname, self.image_counter)
        self.image_counter += 1
        im.flipud_out()
        rows, cols, buf = im.as_rgba_str()
        _png.write_png(buf, cols, rows, os.path.join(path, fname_img))

        # reference the image in the pgf picture
        writeln(self.fh, r"\begin{pgfscope}")
        self._print_pgf_clip(gc)
        h, w = im.get_size_out()
        f = 1. / self.dpi  # from display coords to inch
        writeln(self.fh, r"\pgftext[at=\pgfqpoint{%fin}{%fin},left,bottom]{\pgfimage[interpolate=true,width=%fin,height=%fin]{%s}}" % (x * f, y * f, w * f, h * f, fname_img))
        writeln(self.fh, r"\end{pgfscope}") 
Example #6
Source File: backend_agg.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()
        original_dpi = renderer.dpi
        renderer.dpi = self.figure.dpi
        if is_string_like(filename_or_obj):
            filename_or_obj = open(filename_or_obj, 'wb')
            close = True
        else:
            close = False
        try:
            _png.write_png(renderer._renderer.buffer_rgba(),
                           renderer.width, renderer.height,
                           filename_or_obj, self.figure.dpi)
        finally:
            if close:
                filename_or_obj.close()
        renderer.dpi = original_dpi 
Example #7
Source File: backend_pgf.py    From ImageFusion with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # TODO: Almost no documentation for the behavior of this function.
        #       Something missing?

        # save the images to png files
        path = os.path.dirname(self.fh.name)
        fname = os.path.splitext(os.path.basename(self.fh.name))[0]
        fname_img = "%s-img%d.png" % (fname, self.image_counter)
        self.image_counter += 1
        im.flipud_out()
        rows, cols, buf = im.as_rgba_str()
        _png.write_png(buf, cols, rows, os.path.join(path, fname_img))

        # reference the image in the pgf picture
        writeln(self.fh, r"\begin{pgfscope}")
        self._print_pgf_clip(gc)
        h, w = im.get_size_out()
        f = 1. / self.dpi  # from display coords to inch
        writeln(self.fh, r"\pgftext[at=\pgfqpoint{%fin}{%fin},left,bottom]{\pgfimage[interpolate=true,width=%fin,height=%fin]{%s}}" % (x * f, y * f, w * f, h * f, fname_img))
        writeln(self.fh, r"\end{pgfscope}") 
Example #8
Source File: backend_pdf.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _writePng(self, data):
        """
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        """
        buffer = BytesIO()
        _png.write_png(data, buffer)
        buffer.seek(8)
        while True:
            length, type = struct.unpack(b'!L4s', buffer.read(8))
            if type == b'IDAT':
                data = buffer.read(length)
                if len(data) != length:
                    raise RuntimeError("truncated data")
                self.currentstream.write(data)
            elif type == b'IEND':
                break
            else:
                buffer.seek(length, 1)
            buffer.seek(4, 1)   # skip CRC 
Example #9
Source File: backend_agg.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()
        original_dpi = renderer.dpi
        renderer.dpi = self.figure.dpi

        version_str = 'matplotlib version ' + __version__ + \
            ', http://matplotlib.org/'
        metadata = OrderedDict({'Software': version_str})
        user_metadata = kwargs.pop("metadata", None)
        if user_metadata is not None:
            metadata.update(user_metadata)

        try:
            with cbook.open_file_cm(filename_or_obj, "wb") as fh:
                _png.write_png(renderer._renderer, fh,
                               self.figure.dpi, metadata=metadata)
        finally:
            renderer.dpi = original_dpi 
Example #10
Source File: backend_pgf.py    From Computable with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # TODO: Almost no documentation for the behavior of this function.
        #       Something missing?

        # save the images to png files
        path = os.path.dirname(self.fh.name)
        fname = os.path.splitext(os.path.basename(self.fh.name))[0]
        fname_img = "%s-img%d.png" % (fname, self.image_counter)
        self.image_counter += 1
        im.flipud_out()
        rows, cols, buf = im.as_rgba_str()
        _png.write_png(buf, cols, rows, os.path.join(path, fname_img))

        # reference the image in the pgf picture
        writeln(self.fh, r"\begin{pgfscope}")
        self._print_pgf_clip(gc)
        h, w = im.get_size_out()
        f = 1. / self.dpi  # from display coords to inch
        writeln(self.fh, r"\pgftext[at=\pgfqpoint{%fin}{%fin},left,bottom]{\pgfimage[interpolate=true,width=%fin,height=%fin]{%s}}" % (x * f, y * f, w * f, h * f, fname_img))
        writeln(self.fh, r"\end{pgfscope}") 
Example #11
Source File: backend_agg.py    From Computable with MIT License 6 votes vote down vote up
def print_png(self, filename_or_obj, *args, **kwargs):
        FigureCanvasAgg.draw(self)
        renderer = self.get_renderer()
        original_dpi = renderer.dpi
        renderer.dpi = self.figure.dpi
        if is_string_like(filename_or_obj):
            filename_or_obj = open(filename_or_obj, 'wb')
            close = True
        else:
            close = False
        try:
            _png.write_png(renderer._renderer.buffer_rgba(),
                           renderer.width, renderer.height,
                           filename_or_obj, self.figure.dpi)
        finally:
            if close:
                filename_or_obj.close()
        renderer.dpi = original_dpi 
Example #12
Source File: image.py    From ImageFusion with MIT License 5 votes vote down vote up
def write_png(self, fname, noscale=False):
        """Write the image to png file with fname"""
        im = self.make_image()
        if im is None:
            return
        if noscale:
            numrows, numcols = im.get_size()
            im.reset_matrix()
            im.set_interpolation(0)
            im.resize(numcols, numrows)
        im.flipud_out()
        rows, cols, buffer = im.as_rgba_str()
        _png.write_png(buffer, cols, rows, fname) 
Example #13
Source File: image.py    From ImageFusion with MIT License 5 votes vote down vote up
def write_png(self, fname):
        """Write the image to png file with fname"""
        im = self.make_image()
        rows, cols, buffer = im.as_rgba_str()
        _png.write_png(buffer, cols, rows, fname) 
Example #14
Source File: backend_webagg_core.py    From CogAlg with MIT License 5 votes vote down vote up
def get_diff_image(self):
        if self._png_is_old:
            renderer = self.get_renderer()

            # The buffer is created as type uint32 so that entire
            # pixels can be compared in one numpy call, rather than
            # needing to compare each plane separately.
            buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32)
                    .reshape((renderer.height, renderer.width)))

            # If any pixels have transparency, we need to force a full
            # draw as we cannot overlay new on top of old.
            pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,))

            if self._force_full or np.any(pixels[:, :, 3] != 255):
                self.set_image_mode('full')
                output = buff
            else:
                self.set_image_mode('diff')
                last_buffer = (np.frombuffer(self._last_renderer.buffer_rgba(),
                                             dtype=np.uint32)
                               .reshape((renderer.height, renderer.width)))
                diff = buff != last_buffer
                output = np.where(diff, buff, 0)

            # TODO: We should write a new version of write_png that
            # handles the differencing inline
            buff = _png.write_png(
                output.view(dtype=np.uint8).reshape(output.shape + (4,)),
                None, compression=6, filter=_png.PNG_FILTER_NONE)

            # Swap the renderer frames
            self._renderer, self._last_renderer = (
                self._last_renderer, renderer)
            self._force_full = False
            self._png_is_old = False
            return buff 
Example #15
Source File: compare.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_diff_image(expected, actual, output):
    '''
    Parameters
    ----------
    expected : str
        File path of expected image.
    actual : str
        File path of actual image.
    output : str
        File path to save difference image to.
    '''
    # Drop alpha channels, similarly to compare_images.
    expectedImage = _png.read_png(expected)[..., :3]
    actualImage = _png.read_png(actual)[..., :3]
    actualImage, expectedImage = crop_to_same(
        actual, actualImage, expected, expectedImage)
    expectedImage = np.array(expectedImage).astype(float)
    actualImage = np.array(actualImage).astype(float)
    if expectedImage.shape != actualImage.shape:
        raise ImageComparisonFailure(
            "Image sizes do not match expected size: {} "
            "actual size {}".format(expectedImage.shape, actualImage.shape))
    absDiffImage = np.abs(expectedImage - actualImage)

    # expand differences in luminance domain
    absDiffImage *= 255 * 10
    save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8)
    height, width, depth = save_image_np.shape

    # The PDF renderer doesn't produce an alpha channel, but the
    # matplotlib PNG writer requires one, so expand the array
    if depth == 3:
        with_alpha = np.empty((height, width, 4), dtype=np.uint8)
        with_alpha[:, :, 0:3] = save_image_np
        save_image_np = with_alpha

    # Hard-code the alpha channel to fully solid
    save_image_np[:, :, 3] = 255

    _png.write_png(save_image_np, output) 
Example #16
Source File: image.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def write_png(self, fname):
        """Write the image to png file with fname"""
        im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
                          bytes=True, norm=True)
        _png.write_png(im, fname) 
Example #17
Source File: backend_webagg_core.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def get_diff_image(self):
        if self._png_is_old:
            renderer = self.get_renderer()

            # The buffer is created as type uint32 so that entire
            # pixels can be compared in one numpy call, rather than
            # needing to compare each plane separately.
            buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32)
                    .reshape((renderer.height, renderer.width)))

            # If any pixels have transparency, we need to force a full
            # draw as we cannot overlay new on top of old.
            pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,))

            if self._force_full or np.any(pixels[:, :, 3] != 255):
                self.set_image_mode('full')
                output = buff
            else:
                self.set_image_mode('diff')
                last_buffer = (np.frombuffer(self._last_renderer.buffer_rgba(),
                                             dtype=np.uint32)
                               .reshape((renderer.height, renderer.width)))
                diff = buff != last_buffer
                output = np.where(diff, buff, 0)

            # TODO: We should write a new version of write_png that
            # handles the differencing inline
            buff = _png.write_png(
                output.view(dtype=np.uint8).reshape(output.shape + (4,)),
                None, compression=6, filter=_png.PNG_FILTER_NONE)

            # Swap the renderer frames
            self._renderer, self._last_renderer = (
                self._last_renderer, renderer)
            self._force_full = False
            self._png_is_old = False
            return buff 
Example #18
Source File: backend_pdf.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _writePng(self, data):
        """
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        """

        buffer = BytesIO()
        _png.write_png(data, buffer)
        buffer.seek(8)
        written = 0
        header = bytearray(8)
        while True:
            n = buffer.readinto(header)
            assert n == 8
            length, type = struct.unpack(b'!L4s', bytes(header))
            if type == b'IDAT':
                data = bytearray(length)
                n = buffer.readinto(data)
                assert n == length
                self.currentstream.write(bytes(data))
                written += n
            elif type == b'IEND':
                break
            else:
                buffer.seek(length, 1)
            buffer.seek(4, 1)   # skip CRC 
Example #19
Source File: mathtext.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
        """
        Writes a tex expression to a PNG file.

        Returns the offset of the baseline from the bottom of the
        image in pixels.

        *filename*
            A writable filename or fileobject

        *texstr*
            A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'

        *color*
            A valid matplotlib color argument

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points

        Returns the offset of the baseline from the bottom of the
        image in pixels.
        """
        rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
        _png.write_png(rgba, filename)
        return depth 
Example #20
Source File: backend_pdf.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _writePng(self, data):
        """
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        """

        buffer = BytesIO()
        _png.write_png(data, buffer)
        buffer.seek(8)
        written = 0
        header = bytearray(8)
        while True:
            n = buffer.readinto(header)
            assert n == 8
            length, type = struct.unpack(b'!L4s', bytes(header))
            if type == b'IDAT':
                data = bytearray(length)
                n = buffer.readinto(data)
                assert n == length
                self.currentstream.write(bytes(data))
                written += n
            elif type == b'IEND':
                break
            else:
                buffer.seek(length, 1)
            buffer.seek(4, 1)   # skip CRC 
Example #21
Source File: mathtext.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
        """
        Writes a tex expression to a PNG file.

        Returns the offset of the baseline from the bottom of the
        image in pixels.

        *filename*
            A writable filename or fileobject

        *texstr*
            A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'

        *color*
            A valid matplotlib color argument

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points

        Returns the offset of the baseline from the bottom of the
        image in pixels.
        """
        rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
        _png.write_png(rgba, filename)
        return depth 
Example #22
Source File: compare.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def save_diff_image(expected, actual, output):
    '''
    Parameters
    ----------
    expected : str
        File path of expected image.
    actual : str
        File path of actual image.
    output : str
        File path to save difference image to.
    '''
    # Drop alpha channels, similarly to compare_images.
    expectedImage = _png.read_png(expected)[..., :3]
    actualImage = _png.read_png(actual)[..., :3]
    actualImage, expectedImage = crop_to_same(
        actual, actualImage, expected, expectedImage)
    expectedImage = np.array(expectedImage).astype(float)
    actualImage = np.array(actualImage).astype(float)
    if expectedImage.shape != actualImage.shape:
        raise ImageComparisonFailure(
            "Image sizes do not match expected size: {} "
            "actual size {}".format(expectedImage.shape, actualImage.shape))
    absDiffImage = np.abs(expectedImage - actualImage)

    # expand differences in luminance domain
    absDiffImage *= 255 * 10
    save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8)
    height, width, depth = save_image_np.shape

    # The PDF renderer doesn't produce an alpha channel, but the
    # matplotlib PNG writer requires one, so expand the array
    if depth == 3:
        with_alpha = np.empty((height, width, 4), dtype=np.uint8)
        with_alpha[:, :, 0:3] = save_image_np
        save_image_np = with_alpha

    # Hard-code the alpha channel to fully solid
    save_image_np[:, :, 3] = 255

    _png.write_png(save_image_np, output) 
Example #23
Source File: image.py    From CogAlg with MIT License 5 votes vote down vote up
def write_png(self, fname):
        """Write the image to png file with fname"""
        from matplotlib import _png
        im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
                          bytes=True, norm=True)
        _png.write_png(im, fname) 
Example #24
Source File: image.py    From Computable with MIT License 5 votes vote down vote up
def write_png(self, fname):
        """Write the image to png file with fname"""
        im = self.make_image()
        rows, cols, buffer = im.as_rgba_str()
        _png.write_png(buffer, cols, rows, fname) 
Example #25
Source File: backend_pgf.py    From CogAlg with MIT License 5 votes vote down vote up
def draw_image(self, gc, x, y, im, transform=None):
        # docstring inherited

        h, w = im.shape[:2]
        if w == 0 or h == 0:
            return

        # save the images to png files
        path = os.path.dirname(self.fh.name)
        fname = os.path.splitext(os.path.basename(self.fh.name))[0]
        fname_img = "%s-img%d.png" % (fname, self.image_counter)
        self.image_counter += 1
        _png.write_png(im[::-1], os.path.join(path, fname_img))

        # reference the image in the pgf picture
        writeln(self.fh, r"\begin{pgfscope}")
        self._print_pgf_clip(gc)
        f = 1. / self.dpi  # from display coords to inch
        if transform is None:
            writeln(self.fh,
                    r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))
            w, h = w * f, h * f
        else:
            tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
            writeln(self.fh,
                    r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %
                    (tr1 * f, tr2 * f, tr3 * f, tr4 * f,
                     (tr5 + x) * f, (tr6 + y) * f))
            w = h = 1  # scale is already included in the transform
        interp = str(transform is None).lower()  # interpolation in PDF reader
        writeln(self.fh,
                r"\pgftext[left,bottom]"
                r"{\pgfimage[interpolate=%s,width=%fin,height=%fin]{%s}}" %
                (interp, w, h, fname_img))
        writeln(self.fh, r"\end{pgfscope}") 
Example #26
Source File: mathtext.py    From CogAlg with MIT License 5 votes vote down vote up
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
        r"""
        Render a tex expression to a PNG file.

        Parameters
        ----------
        filename
            A writable filename or fileobject.
        texstr : str
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
        color : color
            The text color.
        dpi : float
            The dots-per-inch setting used to render the text.
        fontsize : int
            The font size in points.

        Returns
        -------
        depth : int
            Offset of the baseline from the bottom of the image, in pixels.
        """
        from matplotlib import _png
        rgba, depth = self.to_rgba(
            texstr, color=color, dpi=dpi, fontsize=fontsize)
        _png.write_png(rgba, filename)
        return depth 
Example #27
Source File: image.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def write_png(self, fname):
        """Write the image to png file with fname"""
        im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
                          bytes=True, norm=True)
        _png.write_png(im, fname) 
Example #28
Source File: backend_webagg_core.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def get_diff_image(self):
        if self._png_is_old:
            renderer = self.get_renderer()

            # The buffer is created as type uint32 so that entire
            # pixels can be compared in one numpy call, rather than
            # needing to compare each plane separately.
            buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32)
                    .reshape((renderer.height, renderer.width)))

            # If any pixels have transparency, we need to force a full
            # draw as we cannot overlay new on top of old.
            pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,))

            if self._force_full or np.any(pixels[:, :, 3] != 255):
                self.set_image_mode('full')
                output = buff
            else:
                self.set_image_mode('diff')
                last_buffer = (np.frombuffer(self._last_renderer.buffer_rgba(),
                                             dtype=np.uint32)
                               .reshape((renderer.height, renderer.width)))
                diff = buff != last_buffer
                output = np.where(diff, buff, 0)

            # TODO: We should write a new version of write_png that
            # handles the differencing inline
            buff = _png.write_png(
                output.view(dtype=np.uint8).reshape(output.shape + (4,)),
                None, compression=6, filter=_png.PNG_FILTER_NONE)

            # Swap the renderer frames
            self._renderer, self._last_renderer = (
                self._last_renderer, renderer)
            self._force_full = False
            self._png_is_old = False
            return buff 
Example #29
Source File: backend_pdf.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _writePng(self, data):
        """
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        """

        buffer = BytesIO()
        _png.write_png(data, buffer)
        buffer.seek(8)
        written = 0
        header = bytearray(8)
        while True:
            n = buffer.readinto(header)
            assert n == 8
            length, type = struct.unpack(b'!L4s', bytes(header))
            if type == b'IDAT':
                data = bytearray(length)
                n = buffer.readinto(data)
                assert n == length
                self.currentstream.write(bytes(data))
                written += n
            elif type == b'IEND':
                break
            else:
                buffer.seek(length, 1)
            buffer.seek(4, 1)   # skip CRC 
Example #30
Source File: mathtext.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
        """
        Writes a tex expression to a PNG file.

        Returns the offset of the baseline from the bottom of the
        image in pixels.

        *filename*
            A writable filename or fileobject

        *texstr*
            A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'

        *color*
            A valid matplotlib color argument

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points

        Returns the offset of the baseline from the bottom of the
        image in pixels.
        """
        rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
        _png.write_png(rgba, filename)
        return depth