API Reference#

Top-level functions#

memeplotlib.meme(template, *lines, font=<object object>, color=<object object>, outline_color=<object object>, outline_width=<object object>, fontsize=<object object>, style=<object object>, backend=None, extension=None, width=None, height=None, layout=None, background=None, overlays=None, template_style=None, show=False, savefig=None, figsize=None, dpi=None, ax=None, **text_kwargs)[source]#

Create a meme from a template with text lines.

The default backend="auto" selects the memegen rendering API for memegen-catalogue templates, and falls back to a Pillow client-side renderer for custom local images or whenever the user supplies a feature memegen can’t express (per-line fontsize, custom outline, Axes.text kwargs).

Parameters:
templatestr

Template identifier – memegen ID, file path, or URL.

*linesstr

Text lines for each text position (top, bottom, etc.).

fontstr, optional

Font family name (default config["font"]).

colorstr, optional

Text fill color (default config["color"]).

outline_colorstr, optional

Text outline color. Passing a non-default value under backend="auto" forces the Pillow backend, since memegen renders a hard-coded black stroke.

outline_widthfloat, optional

Outline stroke width. Passing a non-default value under backend="auto" forces the Pillow backend.

fontsizefloat, optional

Explicit font size in points. Forces the Pillow backend under backend="auto" (memegen always auto-fits).

stylestr, optional

Text transform – "upper", "lower", or "none".

backendstr, optional

"auto" (default), "memegen", "pillow", or "matplotlib" (legacy, draws captions with matplotlib.axes.Axes.text()).

extensionstr, optional

Output format requested from memegen – "png", "jpg", "gif", or "webp".

width, heightint, optional

Output dimensions for memegen-rendered images.

layoutstr, optional

memegen layout (e.g. "top").

backgroundstr, optional

Custom background image URL for memegen.

overlayssequence of dict, optional

Ad-hoc overlay placements forwarded to memegen as repeated style= / center= / scale= query params.

template_stylestr, optional

memegen template-specific style (e.g. "maga" for "ds").

showbool, optional

Whether to call matplotlib.pyplot.show() after rendering.

savefigstr, Path, or None, optional

Path to save the meme image to.

figsizetuple of (float, float) or None, optional

Figure size as (width, height) in inches.

dpiint or None, optional

Dots per inch.

axAxes or None, optional

Existing matplotlib Axes to render onto.

**text_kwargs

Additional keyword arguments forwarded to Axes.text() under the "matplotlib" and "pillow" backends. Passing any text_kwargs under backend="auto" forces the Pillow backend.

Returns:
figmatplotlib.figure.Figure

The matplotlib Figure containing the rendered meme.

axmatplotlib.axes.Axes

The matplotlib Axes containing the rendered meme.

Examples

>>> import memeplotlib as memes
>>> fig, ax = memes.meme("buzz", "memes", "memes everywhere")
>>> fig, ax = memes.meme(
...     "drake", "writing tests", "shipping to prod",
...     font="impact", color="yellow",
... )
>>> fig, ax = memes.meme(
...     "buzz", "hello", "world",
...     fontsize=48,  # forces pillow backend under auto
... )
memeplotlib.memify(fig, *lines, position='top-bottom', font=None, color=None, outline_color=None, outline_width=None, fontsize=None, style=None, show=False, savefig=None, **text_kwargs)[source]#

Add meme-style text to an existing matplotlib figure.

Overlays bold, outlined text on top of any matplotlib figure – useful for turning plots, charts, or other visualizations into memes.

Note

memify always renders text with matplotlib’s Axes.text (the figure isn’t a memegen template, so the API doesn’t apply). The backend parameter on meme() is intentionally not exposed here.

Parameters:
figmatplotlib.figure.Figure

The matplotlib figure to add text to.

*linesstr

Text lines to overlay.

positionstr, optional

Layout – "top-bottom" (default), "top", "bottom", or "center".

fontstr or None, optional

Font family name.

colorstr or None, optional

Text fill color.

outline_colorstr or None, optional

Text outline color.

outline_widthfloat or None, optional

Outline stroke width.

fontsizefloat or None, optional

Font size in points (auto if None).

stylestr or None, optional

Text transform – "upper", "lower", or "none".

showbool, optional

Whether to call matplotlib.pyplot.show() after rendering (default: False).

savefigstr, Path, or None, optional

Path to save the result to.

**text_kwargs

Additional keyword arguments forwarded to Axes.text() for each rendered caption.

Returns:
matplotlib.figure.Figure

The modified Figure.

Examples

>>> import matplotlib.pyplot as plt
>>> import memeplotlib as memes
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 9])
>>> memes.memify(fig, "stonks")
memeplotlib.rc_context(rc=None)[source]#

Temporarily override config keys, restoring originals on exit.

Mirrors matplotlib.rc_context(). Useful for scoped styling that should not leak to other code.

Parameters:
rcMapping or None, optional

Mapping of key-value pairs to apply within the context. If None, the active config is yielded unchanged but still snapshotted for restoration on exit.

Yields:
MemeplotlibConfig

The active config singleton.

Examples

>>> from memeplotlib import config, rc_context
>>> config["font"] = "impact"
>>> with rc_context({"font": "comic", "color": "yellow"}):
...     config["font"]
'comic'
>>> config["font"]
'impact'
memeplotlib.build_memegen_url(template_id, lines, *, api_base, extension='png', template_style=None, font=None, color=None, width=None, height=None, layout=None, background=None, overlays=None)[source]#

Construct a memegen rendering URL.

Parameters:
template_idstr

memegen template identifier (e.g. "buzz", "drake").

linessequence of str

Caption lines in slot order. Empty strings become _ to preserve the slot.

api_basestr

Base URL of the memegen API (e.g. "https://api.memegen.link").

extensionstr, optional

Output format. One of "png", "jpg", "jpeg", "gif", "webp". Default "png".

template_stylestr or None, optional

Template-specific style (e.g. "maga"). May also be an arbitrary image URL for ad-hoc overlays.

fontstr or None, optional

memegen font alias (see MEMEGEN_FONT_ALIASES).

colorstr or None, optional

"fg" or "fg,bg" colour spec (HTML name or hex).

widthint or None, optional

Output width in pixels.

heightint or None, optional

Output height in pixels.

layoutstr or None, optional

Alternate layout (e.g. "top").

backgroundstr or None, optional

Custom background image URL.

overlayssequence of OverlaySpec or None, optional

Ad-hoc overlay placements.

Returns:
str

Fully-formed memegen rendering URL.

Raises:
ValueError

If extension is unsupported.

Examples

>>> build_memegen_url(
...     "buzz", ["memes", "memes everywhere"],
...     api_base="https://api.memegen.link",
... )
'https://api.memegen.link/images/buzz/memes/memes_everywhere.png'
>>> build_memegen_url(
...     "ds", ["a", "b"],
...     api_base="https://api.memegen.link",
...     template_style="maga",
...     font="comic",
...     color="white,black",
...     width=600,
... )
'https://api.memegen.link/images/ds/a/b.png?style=maga&font=comic&...'

Classes#

class memeplotlib.Meme(template, *lines, font=None, color=None, outline_color=None, outline_width=None, fontsize=None, style=None, backend=None, extension=None, width=None, height=None, layout=None, background=None, overlays=None, template_style=None)[source]#

Bases: object

A meme builder with a fluent (chainable) API.

Parameters:
templatestr or Template

Template identifier (memegen ID, file path, URL) or a Template instance.

*linesstr

Initial text lines.

fontstr or None, optional

Font family name.

colorstr or None, optional

Text fill color.

outline_colorstr or None, optional

Text outline color.

outline_widthfloat or None, optional

Outline stroke width.

fontsizefloat or None, optional

Font size in points.

stylestr or None, optional

Text transform – "upper", "lower", or "none".

backendstr or None, optional

Override the rendering backend ("auto", "memegen", "pillow", "matplotlib"). None uses config["backend"].

Examples

>>> from memeplotlib import Meme
>>> Meme("buzz").top("memes").bottom("memes everywhere").show()
>>> m = Meme("drake")
>>> m.top("writing tests")
>>> m.bottom("shipping to prod")
>>> fig, ax = m.render()
>>> m.save("output.png")
>>> # Per-line override forces the Pillow backend.
>>> Meme("buzz").top("hi").line(1, "world", fontsize=48).save("out.png")
top(text)[source]#

Set the top text line (index 0).

Parameters:
textstr

The text to place at the top of the meme.

Returns:
Meme

Self, for method chaining.

bottom(text)[source]#

Set the bottom text line (index 1).

Parameters:
textstr

The text to place at the bottom of the meme.

Returns:
Meme

Self, for method chaining.

text(index, text)[source]#

Set text at a specific line index.

Parameters:
indexint

Zero-based line index.

textstr

The text to place at the given position.

Returns:
Meme

Self, for method chaining.

line(index, text, *, fontsize=None, color=None, font=None, position=None)[source]#

Set text and per-line styling overrides for a single slot.

Passing any of fontsize, color, font, or position forces the Pillow backend on render (memegen has no equivalent).

Parameters:
indexint

Zero-based line index.

textstr

The text to place at the given slot.

fontsizefloat, optional

Override font size for this slot.

colorstr, optional

Override fill colour for this slot.

fontstr, optional

Override font family for this slot.

positionTextPosition, optional

Override the text-box position metadata for this slot.

Returns:
Meme

Self, for method chaining.

with_backend(backend)[source]#

Set the rendering backend.

Parameters:
backendstr

One of "auto", "memegen", "pillow", "matplotlib".

Returns:
Meme

Self, for method chaining.

render(ax=None, figsize=None, dpi=None)[source]#

Render the meme and return the Figure and Axes.

Parameters:
axAxes or None, optional

Existing axes to render onto.

figsizetuple of (float, float) or None, optional

Figure size in inches (width, height).

dpiint or None, optional

Dots per inch.

Returns:
tuple of (Figure, Axes)

The rendered matplotlib Figure and Axes.

show()[source]#

Render and display the meme.

Calls render() if the meme has not been rendered yet, then displays the figure with matplotlib.pyplot.show().

save(path, dpi=None, **kwargs)[source]#

Render and save the meme to a file.

Parameters:
pathstr or Path

Output file path (e.g., "meme.png").

dpiint or None, optional

Dots per inch for the saved image.

**kwargs

Additional keyword arguments passed to matplotlib.figure.Figure.savefig().

class memeplotlib.MemeplotlibConfig[source]#

Bases: MutableMapping[str, Any]

RcParams-style validated mapping of memeplotlib defaults.

Backed by an internal dictionary. Setting an unknown key raises KeyError. Setting a known key with an invalid value raises ValueError. Use rc_context() for scoped overrides.

Notes

Only the keys defined in MemeplotlibConfig.VALID_KEYS are accepted. The set of keys is fixed at class definition time.

Examples

>>> from memeplotlib import config
>>> config["font"] = "comic"
>>> config["dpi"]
150
reset()[source]#

Restore every key to its default value.

class memeplotlib.Template(id, name, image_url, text_positions=<factory>, keywords=<factory>, example=<factory>, lines_count=2, overlays_count=0, styles=<factory>, is_memegen=False)[source]#

Bases: object

A meme template with a background image and text position metadata.

Parameters:
idstr

Template identifier (e.g., "buzz", "drake").

namestr

Human-readable display name.

image_urlstr

URL or local file path to the background image.

text_positionslist of TextPosition, optional

Regions where text lines are rendered. Defaults to a classic top/bottom layout.

keywordslist of str, optional

Search keywords associated with the template.

examplelist of str, optional

Example text lines for the template.

lines_countint, optional

Maximum number of caption slots the template supports (mirrors the memegen lines field). Defaults to 2.

overlays_countint, optional

Number of template-defined overlay slots (mirrors the memegen overlays field). Defaults to 0.

styleslist of str, optional

Template-specific style names (mirrors the memegen styles field). Defaults to [].

is_memegenbool, optional

True if this template was constructed from memegen API metadata; False for custom local files / arbitrary URLs. Used by the rendering dispatcher to decide whether the memegen backend is even reachable.

classmethod from_memegen(template_id, api_base=None)[source]#

Fetch template metadata and blank image from the memegen API.

Parameters:
template_idstr

The memegen template ID (e.g., "buzz", "drake").

api_basestr or None, optional

Override the API base URL.

Returns:
Template

A Template instance with metadata populated from the API.

Raises:
TemplateNotFoundError

If the template ID doesn’t exist in the memegen API.

Examples

>>> t = Template.from_memegen("buzz")
>>> t.name
'Buzz Lightyear'
classmethod from_image(path_or_url, lines=2, name='')[source]#

Create a template from a local image file or URL.

Parameters:
path_or_urlstr

Path to a local image file, or an HTTP(S) URL.

linesint, optional

Number of text lines, which determines the number of text positions (default: 2).

namestr, optional

Display name for the template. Defaults to the file stem.

Returns:
Template

A Template instance backed by the given image.

Examples

>>> t = Template.from_image("photo.jpg")
>>> t = Template.from_image("https://example.com/img.png", lines=3)
get_image(cache=None)[source]#

Return the template background image as a NumPy RGBA array.

Downloads from the image URL if not already loaded or cached.

Parameters:
cacheTemplateCache or None, optional

Cache instance for storing/retrieving downloaded images.

Returns:
numpy.ndarray

RGBA image array with shape (height, width, 4).

class memeplotlib.TemplateRegistry(api_base=None, cache=None)[source]#

Bases: object

Registry that discovers and caches templates from the memegen API.

Parameters:
api_basestr or None, optional

Base URL for the memegen API. Uses config["api_base"] if None.

cacheTemplateCache or None, optional

Cache instance for storing template metadata.

Examples

>>> reg = TemplateRegistry()
>>> results = reg.search("dog")
>>> all_templates = reg.list_all()
get(template_id)[source]#

Get a template by ID, fetching from the API if needed.

Parameters:
template_idstr

The memegen template ID.

Returns:
Template

The resolved template.

Raises:
TemplateNotFoundError

If the template ID is not found.

search(query)[source]#

Search templates by keyword, name, or ID.

Parameters:
querystr

Search term to match against template IDs, names, and keywords (case-insensitive).

Returns:
list of dict

Matching template metadata dicts.

list_all()[source]#

List all available templates.

Returns:
list of dict

Full template catalog from the memegen API.

refresh()[source]#

Force re-fetch of the template catalog from the API.

class memeplotlib.OverlaySpec[source]#

Bases: TypedDict

An ad-hoc overlay placement passed alongside a memegen render.

style#

Overlay image URL, or a template style name.

center#

Overlay anchor as (x, y) fractions in the range [0, 1].

scale#

Overlay scale factor.

Singletons and exceptions#

memeplotlib.config = MemeplotlibConfig()#

RcParams-style validated mapping of memeplotlib defaults.

Backed by an internal dictionary. Setting an unknown key raises KeyError. Setting a known key with an invalid value raises ValueError. Use rc_context() for scoped overrides.

Notes

Only the keys defined in MemeplotlibConfig.VALID_KEYS are accepted. The set of keys is fixed at class definition time.

Examples

>>> from memeplotlib import config
>>> config["font"] = "comic"
>>> config["dpi"]
150
exception memeplotlib._template.TemplateNotFoundError[source]#

Bases: Exception

Raised when a template ID is not found in the memegen API.