In web development, it’s common to fetch images from a remote server and save them locally for further processing. Once saved, you may also need to retrieve the width and height of the image to display it properly on your page. This article demonstrates how to use PHP to achieve these tasks.
Here’s the code that shows how to save a remote image locally and retrieve its width and height:
<?php // Save remote image locally function saveRemoteImage($remoteImageUrl, $localImagePath) { $remoteImageContent = file_get_contents($remoteImageUrl); file_put_contents($localImagePath, $remoteImageContent); } // Get image width and height function getImageSize($localImagePath) { $imageSize = getimagesize($localImagePath); $width = $imageSize[0]; $height = $imageSize[1]; return [ 'width' => $width, 'height' => $height ]; } // Remote image URL and local saving path $remoteImageUrl = 'https://example.com/image.jpg'; $localImagePath = './images/image.jpg'; // Save the remote image locally saveRemoteImage($remoteImageUrl, $localImagePath); // Get image width and height $imageSize = getImageSize($localImagePath); // Output the image width and height echo 'Image Width: ' . $imageSize['width'] . '<br>'; echo 'Image Height: ' . $imageSize['height'] . '<br>'; ?>
The code above contains two functions: `saveRemoteImage` and `getImageSize`.
1. `saveRemoteImage` function:
This function takes two parameters: the URL of the remote image and the local path to save the image. It uses the `file_get_contents` function to fetch the image content from the remote URL, and then saves it locally with `file_put_contents`. This achieves the task of saving a remote image to your local server.
2. `getImageSize` function:
This function uses `getimagesize` to get the image’s width and height from the local path. The `getimagesize` function returns an array containing the image's dimensions and other information. In this example, we only extract the width and height values from the array.
By calling these two functions, we can save the image and get its dimensions, and then output them using `echo` to display the image size on the page.
With the code example provided in this article, you can easily save remote images to your local server and retrieve their width and height using PHP. This is very useful when processing images in web development, especially when you need to dynamically display or adjust image sizes.