Use Pillow to render a page title onto an image, save the image at a publicly reachable URL, then put that URL in the page’s og:image metadata. Open Graph metadata references the image; it does not contain the image file itself. The example below creates a 1200 × 630 PNG, but that size is a design choice—not a universal Open Graph requirement.
What you need
- Python and Pillow installed in the environment that will generate the image.
- A TrueType font file that your script can access. Bundle the font with your application or configure its deployed path; a font installed on your laptop may not exist in a server or container.
- A destination where the generated image can be served at a stable, publicly accessible URL.
Install Pillow with python -m pip install Pillow. The Pillow stable documentation accessed October 3, 2026 identifies version 12.3.0; check the documentation for the version you install if its APIs differ.
Generate an image from the title
Save this as make_og_image.py. Pass the title, font path, and output path as arguments. The script wraps words to fit the canvas, reduces the font size if necessary, centers the result, and writes a PNG.
from pathlib import Path
import argparse
from PIL import Image, ImageDraw, ImageFont
def wrap_title(draw, text, font, max_width):
words = text.split()
if not words:
return []
lines = []
line = words[0]
for word in words[1:]:
candidate = f"{line} {word}"
if draw.textlength(candidate, font=font) <= max_width:
line = candidate
else:
lines.append(line)
line = word
lines.append(line)
return lines
def main():
parser = argparse.ArgumentParser()
parser.add_argument("title")
parser.add_argument("--font", required=True, help="Path to a .ttf or .otf font")
parser.add_argument("--output", default="og-image.png")
args = parser.parse_args()
width, height = 1200, 630
padding = 100
image = Image.new("RGB", (width, height), "#132238")
draw = ImageDraw.Draw(image)
max_width = width - 2 * padding
max_height = height - 2 * padding
font_size = 76
while font_size >= 28:
font = ImageFont.truetype(args.font, font_size)
lines = wrap_title(draw, args.title, font, max_width)
spacing = max(8, font_size // 5)
boxes = [draw.textbbox((0, 0), line, font=font) for line in lines]
text_height = sum(bottom - top for top, _, bottom, _ in boxes)
text_height += spacing * max(0, len(lines) - 1)
widest = max((right - left for left, _, right, _ in boxes), default=0)
if widest <= max_width and text_height <= max_height:
break
font_size -= 2
else:
raise ValueError("Title does not fit; use a shorter title or larger canvas")
y = (height - text_height) // 2
for line, (left, top, right, bottom) in zip(lines, boxes):
line_height = bottom - top
line_width = right - left
x = (width - line_width) // 2 - left
draw.text((x, y - top), line, font=font, fill="#ffffff")
y += line_height + spacing
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
image.save(output, format="PNG")
print(f"Wrote {output} ({width}x{height}, PNG)")
if __name__ == "__main__":
main()
Run it with a real font file path, for example:
python make_og_image.py "How to create an Open Graph image with Python" --font ./fonts/Inter-Bold.ttf --output ./public/images/python-og.png
The program reports the output path and dimensions. The fixed background, padding, color, and canvas dimensions are design choices; change them to match your site. The title is wrapped on spaces, so titles containing unusually long unbroken strings may need a manual break or different wrapping logic.
Recommended Free Tools
#1 Best Overall
- 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.
Why the code measures both width and bounds
ImageDraw.textlength reports rendered advance in pixels, which is useful for deciding whether a candidate line fits. It is not always identical to the text’s bounding box: italics or accents can extend outside the advance. The script also checks textbbox for the selected lines and centers from those bounds. Kerning can make the length of two adjacent strings differ from the length of their combined string, so measure the actual final line rather than adding separate word measurements. Inspect output with the chosen font and real titles before deploying it.
Save as PNG or JPEG
The example explicitly saves PNG. Pillow can infer the format from a filename extension, or you can specify it using format; when saving to a file object rather than a path, provide a format explicitly. For JPEG, use an RGB image and save with image.save(output, format="JPEG", quality=90); choose quality based on the image’s appearance and file-size needs.
Rank #2
- 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.
Publish the image and add Open Graph metadata
Deploy the generated file so it has a stable URL, then place that URL in the HTML head for the page it represents. Replace the example URL and title with the actual page values.
<meta property="og:title" content="How to create an Open Graph image with Python">
<meta property="og:type" content="article">
<meta property="og:url" content="https://example.com/guides/python-og-image">
<meta property="og:image" content="https://example.com/images/python-og.png">
<meta property="og:image:alt" content="A dark blue card with the title How to create an Open Graph image with Python">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
og:image is the image URL representing the page. When you specify it, the Open Graph protocol says to provide og:image:alt as well. The MIME type, width, and height are optional structured properties. Open Graph itself does not prescribe one universal pixel dimension; choose dimensions for the platforms and layout you intend to support, and check their current official guidance separately.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #3
- 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 metadata identifies a URL, not embedded image bytes. Ensure the image is deployed at that URL and that your page outputs the tags in its HTML head. If you publish multiple values for a property, their order can matter: the Open Graph documentation defines the first value as preferred when a property appears more than once.
Troubleshooting
OSError: cannot open resource: The font path is missing or unreadable in the runtime. Use a path that exists in deployment, and include the font in the packaged application if its license permits.- The title clips or looks off-center: Check the rendered PNG with the production font. Text advance and bounding-box dimensions are not interchangeable for every font; increase padding, lower the minimum font size, or shorten the title.
- The script says the title does not fit: A long title can exceed the available height even at the minimum font size. Use a larger canvas, reduce padding or minimum font size, or provide a shorter title.
- The social preview shows no image: Verify that
og:imagecontains the deployed image URL rather than a local filesystem path, and that the URL is reachable by the intended preview consumer. This workflow does not establish any particular platform’s crawler behavior. - The output has the wrong format: Match the extension and explicit
formatargument. Pillow may infer format from a filename extension; for file objects, specify the format.
Or skip the browser setup
If the image you need is a screenshot of a rendered page rather than a title card designed in Python, ScreenshotNeo can return an image from one GET request. This is a different workflow from drawing custom typography with Pillow.
Quick Recap
Best Value
- 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.
Rank #4
- 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
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed; and its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up for the free plan.
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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →




