

.. _sphx_glr_gallery_misc_agg_buffer.py:


==========
Agg Buffer
==========

Use backend agg to access the figure canvas as an RGB string and then
convert it to an array and pass it to Pillow for rendering.




.. image:: /gallery/misc/images/sphx_glr_agg_buffer_001.png
    :align: center





.. code-block:: python


    import numpy as np

    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg


    try:
        from PIL import Image
    except ImportError:
        raise SystemExit("Pillow must be installed to run this example")

    plt.plot([1, 2, 3])

    canvas = plt.get_current_fig_manager().canvas

    agg = canvas.switch_backends(FigureCanvasAgg)
    agg.draw()
    s = agg.tostring_rgb()

    # get the width and the height to resize the matrix
    l, b, w, h = agg.figure.bbox.bounds
    w, h = int(w), int(h)

    X = np.fromstring(s, np.uint8).reshape((h, w, 3))

    try:
        im = Image.fromstring("RGB", (w, h), s)
    except Exception:
        im = Image.frombytes("RGB", (w, h), s)

    # Uncomment this line to display the image using ImageMagick's
    # `display` tool.
    # im.show()

**Total running time of the script:** ( 0 minutes  0.136 seconds)



.. only :: html

 .. container:: sphx-glr-footer


  .. container:: sphx-glr-download

     :download:`Download Python source code: agg_buffer.py <agg_buffer.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: agg_buffer.ipynb <agg_buffer.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.readthedocs.io>`_
