How to Optimize Images on Upload Using TinyPNG API in PHP

Do you want to use TinyPNG to optimize images in PHP without making your website slower? For WordPress websites, online stores, or any PHP project that manages user uploads, this detailed tutorial explains how to automatically compress images upon upload.

Large images kill page speed, whether you run a busy blog, a photography portfolio, or an online store with thousands of product photos. By reducing file sizes by up to 70% without sacrificing quality, TinyPNG instantly resolves that issue.

What TinyPNG Is and Why Developers Adore It

TinyPNG is an intelligent image compression API that uses sophisticated quantization and astute selective color reduction to reduce PNG, JPEG, and WebP files. The outcome? files that are significantly smaller and appear the same to the human eye.

Install the Official TinyPNG PHP Client in Seconds using composer command into your existing PHP website:

composer require tinify/tinify

With this single command, you are ready to use tinify APIs and compress image on a go.

Powerful Reasons to Use TinyPNG

  • Cuts image size by 50-80% without visible quality loss
  • Speeds up page load times (Google loves this for SEO)
  • Saves massive bandwidth costs on high-traffic sites
  • Automatically converts to WebP when it gives better results
  • Works perfectly with WordPress media uploads
  • Handles unlimited images with simple monthly plans
  • Supports preservation of metadata (copyright, GPS, etc.)

Get Your TinyPNG API Key

Create a free account at TinyPNG Developer Site. it only takes 30 seconds. Your unique API key is available on the dashboard as soon as you log in. Copy it right away.

You can test everything and even run small sites with the 500 compressions per month that come with the free plan. Plans start incredibly low and scale easily when you need more. To get started, simply insert that key into your code!

TinyPNG API Example PHP: Compress Images on Upload

Here’s a clean, real-world example that optimizes every image as soon as someone uploads it via a form:

<?php
require_once("vendor/autoload.php");

\Tinify\setKey("YOUR_API_KEY_HERE");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
    
    $uploadDir = "uploads/";
    $sourcePath = $_FILES["image"]["tmp_name"];
    $originalName = basename($_FILES["image"]["name"]);
    $targetPath = $uploadDir . $originalName;

    // Move uploaded file first
    move_uploaded_file($sourcePath, $targetPath);

    // Compress using TinyPNG
    try {
        $source = \Tinify\fromFile($targetPath);
        $source->toFile($targetPath); // Overwrites with compressed version
        
        echo "Boom! Image optimized successfully. Original size reduced by " . 
             round((filesize("uploads/".$originalName . "_original") - filesize($targetPath)) / 1024) . " KB.";
             
    } catch (\Tinify\Exception $e) {
        echo "Compression failed: " . $e->getMessage();
    }
}
?>

<!-- Simple upload form -->
<form method="post" enctype="multipart/form-data">
    <p>Choose an image to upload and optimize instantly:</p>
    <input type="file" name="image" accept="image/*" required>
    <button type="submit">Upload & Optimize with TinyPNG</button>
</form>

When user submit this form. It will use package and tinyPNG api to perform image compression and store it to our defined path.

Convert and Optimize to WebP Automatically

You can also use this package to convert image to WebP format as most of the major search engine prefers for page speed improvements.

$source = \Tinify\fromFile($targetPath);
$converted = $source->toWebp();
$converted->toFile($uploadDir . pathinfo($originalName, PATHINFO_FILENAME) . ".webp");

Optimize Images on Upload WordPress

You can use this approach for wordpress site too. Just add this code to your theme’s functions.php file and it will automatically converts all uploaded images:

add_action('wp_handle_upload', 'optimize_image_with_tinypng');

function optimize_image_with_tinypng($upload) {
    if ($upload['type'] == 'image/jpeg' || $upload['type'] == 'image/png' || $upload['type'] == 'image/webp') {
        
        \Tinify\setKey('YOUR_API_KEY_HERE');
        
        try {
            $source = \Tinify\fromFile($upload['file']);
            $source->toFile($upload['file']);
        } catch (\Tinify\Exception $e) {
            // Silently fail or log error in production
            error_log('TinyPNG compression failed: ' . $e->getMessage());
        }
    }
    return $upload;
}

Conclusion

Implementing TinyPNG API in PHP is one of the quickest wins you’ll ever get for site performance. You optimize image using TinyPNG in PHP with just a few lines of code, save bandwidth, boost SEO rankings, and deliver lightning-fast experiences to your visitors.