PHP

Resize Image to Max Dimension

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Shrink an uploaded image so its longest side is no more than $maxDim pixels, preserving aspect ratio. Re-encodes to JPEG at the given quality. Uses the GD extension.
PHP
Raw
<?php
function resizeImageMax(string $srcPath, string $dstPath, int $maxDim = 1024, int $quality = 85): void {
    [$w, $h] = getimagesize($srcPath);
    $scale   = min(1.0, $maxDim / max($w, $h));
    $newW    = (int)round($w * $scale);
    $newH    = (int)round($h * $scale);

    $src  = match (mime_content_type($srcPath)) {
        'image/jpeg' => imagecreatefromjpeg($srcPath),
        'image/png'  => imagecreatefrompng($srcPath),
        'image/gif'  => imagecreatefromgif($srcPath),
        'image/webp' => imagecreatefromwebp($srcPath),
        default      => throw new RuntimeException('Unsupported image type'),
    };
    $dst = imagecreatetruecolor($newW, $newH);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
    imagejpeg($dst, $dstPath, $quality);
    imagedestroy($src);
    imagedestroy($dst);
}

resizeImageMax('/uploads/photo.png', '/uploads/photo-1024.jpg', 1024);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.