{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Convert texts to images\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from io import BytesIO\n\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.figure import Figure\nfrom matplotlib.transforms import IdentityTransform\n\n\ndef text_to_rgba(s, *, dpi, **kwargs):\n # To convert a text string to an image, we can:\n # - draw it on an empty and transparent figure;\n # - save the figure to a temporary buffer using ``bbox_inches=\"tight\",\n # pad_inches=0`` which will pick the correct area to save;\n # - load the buffer using ``plt.imread``.\n #\n # (If desired, one can also directly save the image to the filesystem.)\n fig = Figure(facecolor=\"none\")\n fig.text(0, 0, s, **kwargs)\n with BytesIO() as buf:\n fig.savefig(buf, dpi=dpi, format=\"png\", bbox_inches=\"tight\",\n pad_inches=0)\n buf.seek(0)\n rgba = plt.imread(buf)\n return rgba\n\n\nfig = plt.figure()\nrgba1 = text_to_rgba(r\"IQ: $\\sigma_i=15$\", color=\"blue\", fontsize=20, dpi=200)\nrgba2 = text_to_rgba(r\"some other string\", color=\"red\", fontsize=20, dpi=200)\n# One can then draw such text images to a Figure using `.Figure.figimage`.\nfig.figimage(rgba1, 100, 50)\nfig.figimage(rgba2, 100, 150)\n\n# One can also directly draw texts to a figure with positioning\n# in pixel coordinates by using `.Figure.text` together with\n# `.transforms.IdentityTransform`.\nfig.text(100, 250, r\"IQ: $\\sigma_i=15$\", color=\"blue\", fontsize=20,\n transform=IdentityTransform())\nfig.text(100, 350, r\"some other string\", color=\"red\", fontsize=20,\n transform=IdentityTransform())\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.figure.Figure.figimage`\n - `matplotlib.figure.Figure.text`\n - `matplotlib.transforms.IdentityTransform`\n - `matplotlib.image.imread`\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }