October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Headless Chrome

How to Convert HTML to JPG with PHP

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

To convert HTML to JPG in PHP, render the HTML in a browser engine and save the resulting screenshot as a JPEG. One documented PHP option is Spatie Browsershot, which uses Puppeteer to control headless Chrome. Tell it explicitly to output JPEG: a .jpg filename alone does not select the image format.

What PHP needs to do to make a JPG from HTML

HTML describes a page; it is not itself a bitmap. The conversion therefore has two stages: a browser renders the markup, styles, and—if used—JavaScript, then the rendered pixels are encoded as JPEG. Browsershot is a PHP interface to Puppeteer and headless Chrome, rather than a pure-PHP HTML renderer. That distinction matters when choosing a server: the PHP package is only one part of the runtime.

PHP’s GD extension provides image creation and manipulation functions, including image output functions such as imagepng. The cited PHP manual does not establish GD as a renderer for arbitrary HTML and CSS, so GD alone is not a substitute for a browser when the input is a web page. It can be useful for later image processing, but first the page must be rendered.

Prerequisites and installation checks

  • Use a PHP version compatible with the Browsershot version you install. Packagist metadata for Browsershot 5.4.0, published May 26, 2026, lists PHP ^8.2, ext-fileinfo, ext-json, spatie/temporary-directory ^2.0, and symfony/process ^6.0|^7.0|^8.0. Requirements can change; verify the metadata for the release actually installed at Packagist.
  • Install Browsershot through Composer, then configure the Node.js, Puppeteer, and headless Chrome components needed by your chosen Browsershot setup. The PHP code below assumes those components are available and configured; it does not install or configure them.
  • Check that your deployment environment allows PHP to start the browser process and that Chrome can run there. Hosting compatibility was not established for any particular provider.

Use the package’s versioned documentation alongside your installed release: the examples here follow the v4 usage documentation. For deployment, confirm both the package requirements and browser-runtime setup for the versions you actually run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Convert an HTML string to JPG

This example renders a self-contained HTML string, sets a 1200 × 800 browser viewport, requests JPEG output at quality 90, and saves it beside the PHP script. Quality 90 is an illustrative setting, not an official Spatie recommendation.

<?php

use SpatieBrowsershotBrowsershot;

$html = '<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <style>
    body { font: 20px Arial, sans-serif; margin: 40px; }
    h1 { color: #174ea6; }
  </style>
</head>
<body>
  <h1>Hello from PHP</h1>
  <p>This page will be rendered as a JPEG.</p>
</body>
</html>';

$output = __DIR__ . '/output.jpg';

Browsershot::html($html)
    ->setScreenshotType('jpeg', 90)
    ->windowSize(1200, 800)
    ->save($output);

echo "Saved: {$output}";

The key format setting is setScreenshotType('jpeg', 90). The official image documentation demonstrates JPEG output with setScreenshotType('jpeg', 100). JPEG is lossy and does not preserve transparency; if transparency or crisp text and line art matter more than JPG compatibility or file size, consider whether another supported image format better fits the job.

Convert a URL or local HTML file

Render a public webpage

Use Browsershot::url() when the input is a URL. The browser must be able to reach that address from the machine running PHP.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
<?php

use SpatieBrowsershotBrowsershot;

Browsershot::url('https://example.com')
    ->setScreenshotType('jpeg', 90)
    ->windowSize(1200, 800)
    ->save(__DIR__ . '/page.jpg');

Render an HTML file

Read the file into a string and pass it to html(). For pages that refer to local images, stylesheets, or scripts, remember that their paths must make sense from the browser process’s point of view. A file path that PHP can read is not automatically a URL or a browser-loadable asset reference.

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.
<?php

use SpatieBrowsershotBrowsershot;

$file = __DIR__ . '/page.html';
$html = file_get_contents($file);

if ($html === false) {
    throw new RuntimeException("Could not read {$file}");
}

Browsershot::html($html)
    ->setScreenshotType('jpeg', 90)
    ->windowSize(1200, 800)
    ->save(__DIR__ . '/page.jpg');

For more complex pages, prefer a URL or arrange assets so the browser can load them correctly. Check the rendered result when relative links, authenticated content, or scripts affect what appears in the screenshot.

Choose the screenshot dimensions and region

Browsershot’s image API documents viewport sizing, clipping, element selection, full-page screenshots, and base64 output. Choose the capture based on what the JPG is for:

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
  • Viewport screenshot: set the browser window dimensions when the desired output is a specific visible viewport.
  • Full-page capture: use the documented full-page option when the entire page should be captured rather than only the initial viewport.
  • Clipped region or element: use the documented clipping or element-selection capabilities when only a component is needed.
  • Base64 output: use the documented base64 approach when the application needs image data rather than a file written directly to disk.

Consult Spatie’s image documentation for the exact method signatures supported by your installed version. A larger viewport or full-page capture can result in a larger image and more browser work; choose dimensions appropriate to the destination instead of capturing more than needed.

Make the rendering predictable and safe

Keep HTML and assets available

A screenshot reflects what Chrome successfully rendered. If stylesheets, fonts, images, or scripts fail to load, the output can be incomplete even when saving the JPEG succeeds. Ensure the browser process can access required assets, and avoid depending on temporary local paths or resources that disappear before rendering finishes.

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

Validate untrusted input

Spatie states that the user is responsible for validating URLs and HTML passed to Browsershot. Do not accept arbitrary visitor-supplied URLs or markup and render them without an application-specific validation and security review. Rendering untrusted input can expose the server to unwanted network requests or resource consumption. The documentation’s warning is not a complete security-hardening guide; assess the risks and controls for your own application. See Spatie’s URL and HTML validation guidance.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Separate rendering from image processing

If you need to resize or otherwise manipulate the resulting image, treat that as a separate step after browser rendering. GD’s documented role is PHP image functions, not arbitrary HTML/CSS layout. This separation makes it easier to identify whether a problem is in page rendering or in later image processing.

Troubleshooting common failures

  • The file is PNG or not recognized as JPEG: set the screenshot type explicitly to jpeg; a .jpg extension does not encode the image.
  • PHP reports missing classes or incompatible package requirements: verify that Composer installed Browsershot and that your PHP version and extensions meet the requirements of the installed package release.
  • The browser process fails to start: confirm that the Node/Puppeteer/Chrome components are installed and that the PHP process can execute them in the deployment environment. Check the runtime configuration for the Browsershot version you use.
  • The screenshot is blank or missing assets: confirm that the browser can reach the URL and that referenced files, stylesheets, and scripts are accessible to it. A path readable by PHP may not resolve for Chrome.
  • The result cuts off the page: a normal viewport captures only its visible area. Use the full-page option documented for your version when the whole page is required, or choose a deliberate clip or element capture.
  • Output size or processing time is excessive: reduce the viewport or capture region, and avoid full-page capture where a component or viewport is sufficient. No universal runtime or output-size figure is established; results depend on the page and runtime.
  • Rendering untrusted URLs or markup: stop and add application-appropriate validation before passing values to Browsershot. The package maintainer explicitly places this responsibility on the caller.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need a screenshot from PHP without installing and maintaining a browser runtime on your own server, you can call ScreenshotNeo, a website screenshot API and MCP server for developers. Its API returns PNG, JPEG, WebP, or PDF output from one GET request. The service says it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. AI agents can use its MCP server tools: take_screenshot, get_page_info, and capture_pdf.

For PHP, use cURL to make the GET request and save the response body. Replace the URL and provide your API key. The API’s request options and output controls are documented at ScreenshotNeo’s API docs.

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

$apiKey = 'YOUR_API_KEY';
$url = 'https://stripe.com';
$endpoint = 'https://api.screenshotneo.com/v1/shot';

$query = http_build_query([
    'access_key' => $apiKey,
    'url' => $url,
]);

$ch = curl_init($endpoint . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 90,
]);

$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($body === false) {
    throw new RuntimeException("Screenshot request failed: {$error}");
}
if ($status < 200 || $status >= 300) {
    throw new RuntimeException("Screenshot API returned HTTP {$status}");
}

file_put_contents(__DIR__ . '/shot.webp', $body);

The example follows the supplied one-call API pattern and writes the returned image bytes to a file; request format and available parameters are described in the docs. ScreenshotNeo offers 1,000 screenshots per month free with no card, and paid plans start at $5 for 3,000 screenshots. Sign up for the free plan to try it.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Cost and operational trade-offs

With Browsershot, the application controls the PHP integration and browser environment, but deployment must support the browser runtime as well as PHP. Plan for the operational work of installing and maintaining those components and making assets available to Chrome. No hosting provider compatibility or performance benchmark is established here.

An API avoids managing the browser process yourself, but requires a network request and use of the provider’s service and plan limits. For ScreenshotNeo, every feature is available on every plan; its listed monthly plans are:

Plan Monthly price Included shots per month
Free $0 1,000; no card required
Starter $5 3,000
Growth $15 15,000
Pro $39 60,000
Scale $99 250,000
Business $249 1,000,000

Yearly billing gives two months free. These are the listed plan prices and allowances; check the ScreenshotNeo site for current plan details before choosing.

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

Which approach fits?

  • Choose Browsershot when you want a PHP-controlled browser renderer and can run its Node/Puppeteer/Chrome requirements in your environment.
  • Choose a screenshot API when you prefer not to operate the browser runtime yourself or need service features such as consent cleanup, billing verdicts, or an MCP interface for AI agents.
  • Use GD after rendering if your workflow needs PHP image manipulation; do not treat it as the HTML rendering stage.

Frequently Asked Questions

Does changing the output filename to .jpg convert a PNG screenshot into JPEG?

No. Select JPEG output in the screenshot configuration; the filename extension only names the saved file.

Can Browsershot render JavaScript-driven pages?

Browsershot uses Puppeteer to control headless Chrome, so the rendering is browser-based. Whether a particular page finishes rendering with all expected content depends on its scripts, resources, and runtime setup.

Can I use PHP GD by itself to convert arbitrary HTML and CSS into a JPG?

The PHP GD manual documents image functions, not browser-like rendering of arbitrary HTML and CSS. Use a browser renderer for that stage.

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.