To generate an Open Graph image in PHP, create a bitmap (for example, with PHP’s GD extension), save it somewhere with a stable, publicly fetchable URL, and put that URL in the page’s og:image metadata. These are two separate jobs: drawing an image does not add it to a page’s social-preview metadata.
This guide starts with a small GD implementation, then shows the page markup, library choices, deployment checks, and common failure fixes. GD’s supported formats depend on how PHP was built, so verify the extensions and formats available in the environment where the code will run.
What an Open Graph image needs
Open Graph metadata describes a page to systems that consume its preview information. The protocol’s required properties are og:title, og:type, og:image, and og:url. The image itself must be available at the URL in og:image; generating bytes on a server is not enough if preview fetchers cannot retrieve them.
The protocol also defines image structured properties: og:image:secure_url, og:image:type, og:image:width, og:image:height, and og:image:alt. Keep these next to the corresponding og:image declaration because they describe that image. If a property is repeated with conflicting values, the first value in document order takes precedence. See the Open Graph protocol.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →#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.
The protocol gives 400 by 300 pixels as an example, not a universal requirement. Social services can have different or changing preview rules; check the current guidance for the platforms you need to support rather than relying on one size as a guarantee.
Generate a simple image with PHP GD
GD is PHP’s built-in image library when enabled in the PHP build. The example below creates a 1200 by 630 PNG with a background and a title, saves it to a file, and releases its image resource. Change the output directory and public URL to match your application.
Save this as a PHP script and run it from the command line or invoke it from an application route:
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.
<?php
declare(strict_types=1);
// Confirm GD is available in the PHP runtime that executes this script.
if (!extension_loaded('gd')) {
throw new RuntimeException('The GD extension is not enabled.');
}
$info = gd_info();
if (empty($info['PNG Support'])) {
throw new RuntimeException('This GD build does not support PNG output.');
}
$width = 1200;
$height = 630;
$image = imagecreatetruecolor($width, $height);
if ($image === false) {
throw new RuntimeException('Could not create the image canvas.');
}
$background = imagecolorallocate($image, 24, 35, 58);
$foreground = imagecolorallocate($image, 255, 255, 255);
$accent = imagecolorallocate($image, 83, 190, 180);
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $background);
imagefilledrectangle($image, 0, 0, 18, $height - 1, $accent);
$title = 'A page-specific preview image';
// Built-in bitmap font: portable, but limited in size and typographic control.
$font = 5;
$textWidth = imagefontwidth($font) * strlen($title);
$x = max(40, (int) (($width - $textWidth) / 2));
$y = (int) (($height - imagefontheight($font)) / 2);
imagestring($image, $font, $x, $y, $title, $foreground);
$outputPath = __DIR__ . '/public/og/example.png';
$outputDir = dirname($outputPath);
if (!is_dir($outputDir) && !mkdir($outputDir, 0755, true) && !is_dir($outputDir)) {
imagedestroy($image);
throw new RuntimeException('Could not create the output directory.');
}
if (!imagepng($image, $outputPath)) {
imagedestroy($image);
throw new RuntimeException('Could not write the PNG file.');
}
imagedestroy($image);
echo "Wrote {$outputPath}n";
The example uses GD’s built-in bitmap font so it does not assume a TrueType font is installed. For more control over typography, GD can use a font file with its FreeType functions when FreeType support is enabled. Check gd_info() on the deployed PHP build before depending on PNG, JPEG, WebP, or FreeType capabilities: the available functions and formats can differ by build. PHP documents GD’s image creation, manipulation, and output functions at the GD manual.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesFor dynamic pages, derive the text from trusted page data, and choose a deterministic filename or cache key for each page/version. If the image is generated on demand, set the response content type to the format actually emitted and make sure the route can be fetched without a user login. Saving a file or storing the returned binary in object storage is often simpler for stable URLs and caching than computing the image on every preview request.
Add the generated image to the page metadata
Suppose the saved PNG is publicly served at https://example.com/og/example.png. Add its URL and the page URL to the HTML document’s head. The structured properties immediately following og:image describe that image.
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.
<head>
<title>A page-specific preview image</title>
<meta property="og:title" content="A page-specific preview image">
<meta property="og:type" content="website">
<meta property="og:url" content="https://example.com/article/example">
<meta property="og:image" content="https://example.com/og/example.png">
<meta property="og:image:secure_url" content="https://example.com/og/example.png">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="A dark blue graphic titled A page-specific preview image">
</head>
In a PHP template, escape variable content before placing it in an HTML attribute. For example, use htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') for text and URL values that may contain user- or database-provided characters. Use a canonical, absolute URL for the page and image, and ensure the image URL returns the image rather than an HTML error page.
Choose between GD, Imagine, and a generator package
The right option depends on whether you need a small native solution, a general image API, or a higher-level OG-image workflow. The package requirements below are version-specific; verify the constraints for the version you install and the PHP runtime that will execute it.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
| Option | Good fit | Dependencies and checks |
|---|---|---|
| PHP GD functions | Simple backgrounds, text, shapes, and direct image output in PHP. | GD must be enabled, and the deployed build must support the output format and any font features you use. Inspect gd_info(). |
| Imagine | A general object-oriented API for drawing text, resizing, cropping, masking, and other image operations. | The project documentation lists PHP 7.1+ and one of GD2, Imagick, or Gmagick. Confirm the chosen driver and its feature support. See Imagine documentation. |
| The OG | A package-oriented, styling-focused API for generating OG images, with title, description, URL, backgrounds, and save-or-return-bytes workflows. | The Packagist listing inspected for version 0.8.0, published 2026-05-16, specifies PHP ^8.3 and intervention/image ^4.0. Those constraints describe that release, not every future version. See The OG on Packagist. |
| abordage/laravel-og-images | A Laravel-focused package option for projects needing an OG-image integration. | Its README lists PHP 8.2+, Laravel 11.x, 12.x, or 13.x, and the Imagick PHP extension. Check the repository for current compatibility. See the package repository. |
Imagine provides a broader abstraction over multiple possible image drivers; a dedicated generator can offer a shorter route to a styled result but brings its own package and extension constraints. These options are not evidence of a performance ranking, and no independent benchmark establishes that one is faster or more reliable for every workload.
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
Make the image reliable in production
Use a stable, fetchable URL
Preview systems need to request the image. Serve it over HTTPS at a URL that does not require session cookies, application login, or a browser-only workflow. If you store bytes outside the web root, use a public object-storage or CDN URL, or an application route that correctly serves the binary. Avoid URLs that expire before a preview fetch occurs.
Keep the format and metadata in agreement
If PHP writes a PNG, use a URL that serves the PNG and declare image/png; use the corresponding values for JPEG or WebP output. Confirm the actual file format instead of inferring it from a filename. The width and height in the metadata should match the emitted image.
Control dynamic content and caching
Generate images from known page fields and escape text for the rendering context. If a title changes, ensure the stored image and its URL do not continue serving an obsolete version. A versioned filename or a cache policy coordinated with your page metadata can help keep the preview and image in sync. Avoid accepting arbitrary remote image input without validating it; untrusted input can introduce security and resource-use risks.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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.
Check the final page, not just the bitmap
- Open the image URL directly from outside your authenticated session and confirm it returns image bytes.
- Inspect the response status, content type, dimensions, and file format.
- View the rendered page source and confirm the intended Open Graph tags are present in the document head.
- Check that each page has the correct title, canonical page URL, and image URL rather than duplicated or stale metadata.
- Use the target social platform’s current preview or debugging tool to inspect what it fetches; platform-specific cache behavior and constraints should be checked in that platform’s documentation.
Troubleshoot common failures
| Symptom | Likely cause | Fix |
|---|---|---|
Call to undefined function imagecreatetruecolor() |
GD is absent or disabled in the PHP runtime running the script. | Enable/install GD for that PHP version and service, then verify with extension_loaded('gd') and gd_info(). A CLI PHP build and a web-server PHP build may differ. |
| Image output is missing or has the wrong format | The build lacks support for the chosen format, the write failed, or the response header does not match the bytes. | Check the relevant gd_info() capability, test the return value of the output function, inspect the file type, and set the matching content type for HTTP output. |
| Text is clipped or unreadable | The text exceeds the canvas, uses a small built-in font, or relies on an unavailable font file or FreeType support. | Measure or wrap the text, adjust its placement and size, and verify the font path and GD FreeType support if using TrueType rendering. |
| The page preview omits the image | The image URL is private, invalid, blocked, redirects unexpectedly, or returns an error/HTML instead of image bytes; metadata may also be absent or stale. | Fetch the exact URL without a logged-in browser, inspect the response, verify the rendered head tags, and use the platform’s preview/debug tool. |
| Preview shows an older graphic | A cached image or page preview has not updated after the image content changed. | Publish a new versioned image URL and update og:image, then request a refresh using the target platform’s supported tooling. |
| A package cannot install or run | The project’s PHP, framework, image driver, or extension versions do not satisfy the package release requirements. | Read the constraints for the exact release in Composer output and the package’s current documentation; select a compatible version or use GD directly. |
Or skip the browser setup
If your page is available online and you need a screenshot-style graphic as an input to your workflow, ScreenshotNeo is a website screenshot API and MCP server. It does not replace writing Open Graph metadata: you still need to publish the resulting image at a stable URL and add that URL to the page. For a single capture, make one GET request:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for request options. Cookie banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents use screenshot tools, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.
Frequently Asked Questions
Does generating an image automatically add it to Open Graph metadata?
No. Save or serve the image at a fetchable URL, then put that URL in the page’s og:image tag.
Is 1200 by 630 required for every social platform?
No universal requirement is established here. The Open Graph protocol uses 400 by 300 pixels as an example; check the current guidance for the platforms you target.
Can I return the image directly from a PHP route instead of saving a file?
Yes, if the route intentionally serves the binary with the correct content type and a stable, publicly fetchable URL. Saving or storing the bytes is often easier for persistent URLs and caching.
Quick Recap
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.

