Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Flask does not include an Open Graph (OG) image generator. You provide the page route and Jinja template, create an image yourself (commonly with Pillow), and publish a publicly reachable image URL in the page’s og:image tag. A stable, server-rendered image endpoint or object-storage URL works for static and page-specific cards.

This guide builds a complete Flask implementation, explains delivery and caching details, compares local and hosted rendering, and shows how to verify the HTML and image response.

What an Open Graph image requires

The Open Graph protocol uses metadata in the HTML document. At minimum, emit the page title, description and image URL. Companion properties describe the image dimensions, MIME type and alternative text.

<meta property="og:title" content="{{ page.title }}">
<meta property="og:description" content="{{ page.description }}">
<meta property="og:image" content="{{ page.og_image_url }}">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:type" content="image/png">
<meta property="og:image:alt" content="{{ page.og_image_alt }}">

If you publish an og:image, include og:image:alt. The protocol documents width, height and MIME-type properties but does not require one universal pixel size. A practical 2026 baseline from OpenGraphDebug.com is 1200 × 630 pixels; check the channels you target because cropping, formats and crawler behavior differ.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Choose where the image is generated

Generate in your Flask process

Pillow gives Python code direct control over backgrounds, fonts, wrapping, logos and page-specific text. You operate the rendering CPU, fonts, cache and storage, but the result is deterministic and does not require sending content to another service. Flask itself neither requires nor bundles Pillow.

Use a hosted renderer

An image API can render a template from request data. This reduces image-processing code in your application, while introducing credentials, another dependency, network latency, provider terms and data-handling questions. Validate price, availability, formats, dimensions and privacy for your own traffic; the available vendor examples do not establish a universal cost, reliability or quality winner.

Build a dynamic Flask image with Pillow

1. Install the dependencies

python -m pip install Flask Pillow

Install a font available on your deployment system and use an absolute path. A missing font is a common production-only failure, so fail clearly or package the font with your application.

2. Create the application

from io import BytesIO
from pathlib import Path

from flask import Flask, abort, render_template, send_file, url_for
from PIL import Image, ImageDraw, ImageFont

app = Flask(__name__)

PAGES = {
    "flask-og": {
        "title": "Generate Open Graph Images in Flask",
        "description": "A page-specific social preview generated by Python.",
        "og_image_alt": "Open Graph card for Generate Open Graph Images in Flask",
    },
    "pillow": {
        "title": "Drawing OG cards with Pillow",
        "description": "Raster image composition from a Flask endpoint.",
        "og_image_alt": "Open Graph card for Drawing OG cards with Pillow",
    },
}

FONT = Path(__file__).parent / "fonts" / "Inter-Bold.ttf"


def make_og_image(page):
    width, height = 1200, 630
    image = Image.new("RGB", (width, height), "#111827")
    draw = ImageDraw.Draw(image)
    title_font = ImageFont.truetype(str(FONT), 64)
    body_font = ImageFont.truetype(str(FONT), 30)

    draw.rectangle((0, 0, width, 18), fill="#38bdf8")
    draw.text((72, 120), page["title"], font=title_font, fill="white",
              spacing=12, stroke_width=0)
    draw.text((72, 430), page["description"], font=body_font, fill="#cbd5e1")
    return image


@app.get("/article/<slug>")
def article(slug):
    page = PAGES.get(slug)
    if page is None:
        abort(404)
    page = {**page, "og_image_url": url_for("og_image", slug=slug, _external=True)}
    return render_template("article.html", page=page)


@app.get("/og/<slug>.png")
def og_image(slug):
    page = PAGES.get(slug)
    if page is None:
        abort(404)
    image = make_og_image(page)
    output = BytesIO()
    image.save(output, format="PNG", optimize=True)
    output.seek(0)
    response = send_file(output, mimetype="image/png", max_age=3600)
    response.headers["Cache-Control"] = "public, max-age=3600"
    return response


if __name__ == "__main__":
    app.run(debug=True)

url_for(..., _external=True) produces an absolute URL, which is important because preview fetchers are not browsing your local filesystem. Behind a reverse proxy, configure Flask’s trusted proxy settings so the generated scheme and host are the public ones.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

3. Add the Jinja template

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{ page.title }}</title>
  <meta name="description" content="{{ page.description }}">
  <meta property="og:title" content="{{ page.title }}">
  <meta property="og:description" content="{{ page.description }}">
  <meta property="og:image" content="{{ page.og_image_url }}">
  <meta property="og:image:width" content="1200">
  <meta property="og:image:height" content="630">
  <meta property="og:image:type" content="image/png">
  <meta property="og:image:alt" content="{{ page.og_image_alt }}">
</head>
<body><h1>{{ page.title }}</h1></body>
</html>

Keep Jinja autoescaping enabled for titles, descriptions and alt text. Do not apply |safe to untrusted values merely to make metadata appear; HTML escaping and drawing text into a bitmap are separate contexts.

Use static files or object storage instead

For cards that change rarely, generate PNG files during a build or background job and point og:image at a static or object-storage URL. This removes image work from a request. Give each content revision a versioned filename (for example, article-42-v3.png) when the image changes; otherwise intermediary caches may continue serving the old bytes.

For on-demand generation, cache by a stable key such as slug plus content revision. Do not let arbitrary query strings create unlimited image variants. If image text contains user data, enforce length limits and handle missing glyphs, line wrapping and right-to-left text deliberately.

Verification checklist

  1. Request the article URL without JavaScript and inspect the server response HTML.
  2. Confirm og:image is an absolute URL matching the value you intended.
  3. Request that image URL directly and verify a successful response, Content-Type: image/png (or your chosen format), and the actual pixel dimensions.
  4. Check that authentication, robots rules, firewall rules or staging-only hostnames do not prevent preview fetchers from retrieving the image.
  5. Validate the rendered card on every platform you support; platform caches can delay changes.

Common failures and fixes

The preview uses no image

Inspect the final HTML, not a client-side DOM snapshot. If the tag is absent, put it in the server-rendered head. If it is present, fetch the exact image URL from an unauthenticated network and check for redirects, DNS errors and a non-image response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

The image URL points to localhost or HTTP

Use _external=True and configure the production host and HTTPS scheme. A URL that works only on your laptop cannot be fetched by a remote preview service.

Text is clipped or the font is missing

Package the font, use a known absolute path, measure text before drawing, wrap long titles, and test with the longest realistic title. Pillow will not automatically design a responsive layout for you.

Old artwork remains after an edit

Change the image URL when content changes, or use an explicit cache policy and purge the cache you control. Social platforms may retain their own cached copy.

Image generation slows page requests

Generate asynchronously or cache the first result. Pre-render popular pages, keep a bounded cache, and avoid repeatedly loading large source assets. A separate worker or hosted renderer can isolate CPU spikes from Flask web workers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

User text creates unsafe HTML

Leave autoescaping on and never mark untrusted metadata safe. Validate lengths and characters before drawing; do not interpret user text as markup or code.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and cost decisions

Approach Control Operational work Best fit
Pillow endpoint Full layout, fonts and pixels CPU, fonts, caching and deployment Teams that need application-level control
Pre-generated/static files Full output control Build or job pipeline and storage Stable content and predictable traffic
Hosted renderer Depends on API templates and options Credentials, network dependency and provider terms Fast integration without maintaining rendering code

There is no evidence here for a universal break-even price or latency. Measure your request volume, image CPU time, cache hit rate and provider pricing, and decide whether page titles, source images or other data may be sent outside your infrastructure.

Or skip the browser setup

ScreenshotNeo can capture a rendered page through one HTTP request, so you can host an OG-card HTML route and use its image response instead of maintaining browser automation. Cookie and consent banners, newsletter popups and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server gives AI agents tools named take_screenshot, get_page_info and capture_pdf.

For the complete parameter list, see the ScreenshotNeo API documentation. Example (change the URL to your public Flask card route):

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/og-card/flask-og -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/og-card/flask-og"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/og-card/flask-og' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);

The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. Every feature is included on every plan. Sign up for the free plan.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Frequently Asked Questions

Should the OG image endpoint require login?

No. Preview fetchers generally need to retrieve the image without your user session, so publish it at a reachable URL or use a signed URL designed for that access pattern.

Can I return WebP instead of PNG?

Yes, if the target channels accept it. Set the image’s actual MIME type and matching og:image:type, then verify the rendered previews on those channels.

Do I need JavaScript to generate the card?

No. Pillow can compose the bitmap entirely in Python, and Flask can return it directly from an endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Bottom Line

Use Flask and Jinja to publish correct, absolute OG metadata, then generate cards with Pillow, pre-rendered files or a hosted renderer according to your control, operations and privacy needs. Verify both the final HTML and the image response before diagnosing a platform preview.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.