Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk6 min

How to Optimize Images in PHP

A practical PHP image optimization guide: check GD capabilities, resize before encoding, choose formats carefully, preserve transparency, and test real outputs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To optimize images in PHP, create derivatives at the dimensions your application actually displays, then re-encode them in a format supported by your production server. With GD, first check the installed format support, preserve transparency when it matters, and compare output size and appearance on representative files. There is no single quality setting or format that is best for every image.

Choose an optimization workflow

  1. Set target dimensions. Determine the largest size each image needs in the application. Resize to that size rather than repeatedly serving an oversized original.
  2. Check production support. GD capabilities depend on the PHP build and linked libraries. Inspect the actual environment before relying on WebP or AVIF.
  3. Choose the output format. Consider visual quality, byte size, transparency or animation needs, deployment support, and delivery requirements.
  4. Encode and compare. Test representative images, checking dimensions, output bytes, and appearance. Keep originals if you may need to restore or regenerate derivatives.
  5. Set operational limits. Bound image dimensions, processing time, and memory. Large images can consume substantial resources; memory allocated by a system GD library may not be governed by PHP’s memory_limit.

Check GD support on the server

Do not assume that a format supported by one PHP installation is available on another. PHP’s GD documentation lists support for common formats including JPEG, PNG, GIF, and WebP, but the deployed build and its linked libraries determine actual capabilities. Use gd_info() or imagetypes() to inspect the installed extension; imagetypes() returns a bit-field of formats supported by the linked GD library. See the PHP GD installation documentation.

<?php
if (!extension_loaded('gd')) {
    throw new RuntimeException('The GD extension is not loaded.');
}

$info = gd_info();
var_export($info);
echo PHP_EOL;
echo 'Supported image type flags: ' . imagetypes() . PHP_EOL;

Check this in the same runtime and deployment environment that processes images. A development machine’s capabilities do not establish production support.

Resize and re-encode with GD

This example accepts a local JPEG, PNG, or WebP input, resizes it to fit within a maximum width and height without enlarging it, and writes a WebP derivative. It deliberately checks that the input is decodable and that WebP output is available. Set $quality to a value you have evaluated against your own image mix; PHP documents the quality parameter but does not prescribe a universal best value.

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.
<?php
$sourcePath = __DIR__ . '/upload.jpg';
$outputPath = __DIR__ . '/optimized.webp';
$maxWidth = 1600;
$maxHeight = 1600;
$quality = 82; // Evaluate this value with representative images.

if (!extension_loaded('gd')) {
    throw new RuntimeException('GD is not available.');
}
if (!function_exists('imagewebp')) {
    throw new RuntimeException('This GD build cannot write WebP.');
}

$image = @getimagesize($sourcePath);
if ($image === false) {
    throw new RuntimeException('The input is not a readable image.');
}

[$width, $height, $type] = $image;
$loaders = [
    IMAGETYPE_JPEG => 'imagecreatefromjpeg',
    IMAGETYPE_PNG => 'imagecreatefrompng',
    IMAGETYPE_WEBP => 'imagecreatefromwebp',
];
if (!isset($loaders[$type]) || !function_exists($loaders[$type])) {
    throw new RuntimeException('Unsupported input type or missing GD decoder.');
}

$source = $loaders[$type]($sourcePath);
if ($source === false) {
    throw new RuntimeException('GD could not decode the input.');
}

$scale = min(1, $maxWidth / $width, $maxHeight / $height);
$newWidth = max(1, (int) floor($width * $scale));
$newHeight = max(1, (int) floor($height * $scale));
$target = imagecreatetruecolor($newWidth, $newHeight);
if ($target === false) {
    imagedestroy($source);
    throw new RuntimeException('Could not allocate the output image.');
}

// WebP supports alpha. Preserve it when the source contains transparency.
imagealphablending($target, false);
imagesavealpha($target, true);

if (!imagecopyresampled(
    $target, $source,
    0, 0, 0, 0,
    $newWidth, $newHeight, $width, $height
)) {
    imagedestroy($source);
    imagedestroy($target);
    throw new RuntimeException('Resampling failed.');
}

if (!imagewebp($target, $outputPath, $quality)) {
    imagedestroy($source);
    imagedestroy($target);
    throw new RuntimeException('WebP encoding failed.');
}

imagedestroy($source);
imagedestroy($target);
echo "Wrote {$outputPath} ({$newWidth}x{$newHeight})" . PHP_EOL;

For production uploads, do not treat this sample as a complete upload-security system. Validate and constrain inputs, choose a controlled output path, and handle errors and resource limits appropriate to your application. The PHP imagewebp() manual documents its output and quality argument.

Pick formats based on the image and build

JPEG

JPEG is commonly used for photographic images, but whether it is the best output depends on the application’s delivery requirements and tested results. Re-encoding and resizing may change appearance; compare the result rather than assuming a particular byte reduction.

PNG

PNG is useful where lossless output or transparency is important. PHP’s documentation says imagesavealpha() is meaningful for PNG. If converting a transparent asset to another format, inspect the result and verify alpha handling in the actual encoder and output path.

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.

WebP

GD’s imagewebp() writes WebP and accepts a quality parameter. PHP documents that WebP preserves the full alpha channel. The best setting depends on the content: test photographs, screenshots, logos, and illustrations separately rather than applying one untested value.

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

AVIF

PHP documents GD AVIF support as available from PHP 8.1.0 when built with AVIF support. The build configuration uses --with-avif. Verify the PHP version and production build before making AVIF output part of a required pipeline.

Build configuration details

PHP’s GD installation documentation notes that the WebP configuration switch is --with-webp as of PHP 7.4.0. These are build-time conditions, not guarantees about every installed PHP package. Confirm runtime support using the capability checks above. See PHP’s GD installation page.

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.

Preserve transparency and other important properties

For logos, overlays, and other assets that need transparent pixels, check that the destination format supports alpha and that the conversion preserves it. PHP specifies that imagesavealpha() is meaningful for PNG, while WebP and AVIF save the full alpha channel. Format support alone does not guarantee that every source property or visual detail survives a conversion, so inspect the encoded output.

  • Compare transparent edges against both light and dark backgrounds.
  • Check dimensions after resizing and verify that the image was not unintentionally enlarged.
  • Test animated inputs separately; a still-image workflow may not preserve animation.
  • Retain the original when later recovery or reprocessing matters.

Compare results without assuming a savings percentage

Run the same process on a representative set of your site’s images. Record the source and output dimensions, byte size, and visual acceptability for each relevant format and quality setting. Include photos, screenshots, logos, and images with transparency where applicable. No universal percentage reduction or quality setting follows from the PHP API documentation; the useful choice is the one your test set supports.

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

Use ImageMagick when its controls suit the workload

ImageMagick is another server-side processing option. Its security policy can restrict readable and writable formats and set resource limits. For untrusted uploads, restrict the formats and resources the processing service needs, keep its libraries maintained, and treat policy configuration as one hardening control—not a complete upload-security design. Consult the ImageMagick security policy documentation.

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
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

GD or a format function is missing

Check that GD is loaded in the PHP runtime doing the work, then inspect gd_info() and imagetypes(). If imagewebp() is unavailable, the installed build may not include WebP support; deploy a build with the needed support or select an available output format.

The input cannot be decoded

Confirm the file is a supported image and that the relevant GD decoder exists. A filename extension alone does not establish the file’s actual type. Handle failed reads and decoder errors instead of proceeding with an invalid image resource.

The output is too large or looks poor

Verify the target dimensions first, then test a different format or quality setting on the same representative source files. A quality value is not a universal promise about appearance or byte size.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Transparent areas change appearance

Check destination alpha support and how the image is initialized before resampling. For PNG, PHP documents imagesavealpha() as meaningful; WebP and AVIF save full alpha. Inspect the actual output over contrasting backgrounds.

Processing runs out of memory or stalls

Reduce the maximum accepted dimensions and bound processing time. GD may use memory allocated by its system library outside PHP’s memory_limit, so that setting alone may not contain large-image workloads.

Or skip the browser setup

If your goal is to capture a webpage as an image rather than optimize uploaded image files in PHP, ScreenshotNeo provides a screenshot API and MCP server. One GET request returns a screenshot or PDF; the response identifies the page verdict and billing status. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed; an MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Sign up for ScreenshotNeo’s 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.

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.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.