Current Location: Home> Latest Articles> How to Limit Image Size When Saving Remote Images Using PHP

How to Limit Image Size When Saving Remote Images Using PHP

M66 2025-06-25

How to Limit Image Size When Saving Remote Images Using PHP

With the rapid development of the internet, it has become common to retrieve and save images from the web. To save storage space and improve website loading speed, it’s essential to apply image size restrictions when saving images. This article explains how to use PHP to limit the size of images when saving remote images.

Using the GD Library to Get the Remote Image Size

The GD library in PHP is a powerful image processing tool that supports tasks like resizing and compressing images. First, we need to retrieve the width and height of the remote image using PHP’s built-in getimagesize function. Here is an example code:

$remoteImageUrl = 'http://example.com/remote-image.jpg';
$imageInfo = getimagesize($remoteImageUrl);

if (!$imageInfo) {
    echo 'Failed to retrieve the remote image!';
    return;
}

$remoteImageWidth = $imageInfo[0];
$remoteImageHeight = $imageInfo[1];

With the above code, you can successfully retrieve the width and height of the remote image.

Defining Maximum Dimensions and Applying Size Restrictions

Next, define a maximum width and height for the image and apply the size restriction. If the remote image exceeds the set dimensions, it will be scaled down; otherwise, it will be saved as is. The following is an example code:

$maxWidth = 800;
$maxHeight = 600;

if ($remoteImageWidth > $maxWidth || $remoteImageHeight > $maxHeight) {
    // Calculate the scaling ratio
    $scale = min($maxWidth / $remoteImageWidth, $maxHeight / $remoteImageHeight);

    // Calculate the new dimensions
    $newWidth = $remoteImageWidth * $scale;
    $newHeight = $remoteImageHeight * $scale;

    // Create a new blank image
    $newImage = imagecreatetruecolor($newWidth, $newHeight);

    // Copy and resize the remote image into the new image
    imagecopyresampled($newImage, imagecreatefromjpeg($remoteImageUrl), 0, 0, 0, 0, $newWidth, $newHeight, $remoteImageWidth, $remoteImageHeight);

    // Save the new image to the local server
    imagejpeg($newImage, 'path/to/save/new-image.jpg');

    // Free up memory
    imagedestroy($newImage);
} else {
    // No need to resize, directly save the remote image
    copy($remoteImageUrl, 'path/to/save/remote-image.jpg');
}

Conclusion

With the above method, you can easily implement saving remote images using PHP while applying effective size restrictions. This ensures that the saved images are of a reasonable size, which not only saves server space but also improves website loading efficiency. The process involves: retrieving the remote image size, setting a maximum size, checking if resizing is necessary, and then saving the image.