With the popularity of digital photography, the number of photos being taken is constantly increasing. For photography enthusiasts, understanding photo metadata is very important. This article will show how to use PHP and the Exif extension to extract the focal length of photos, helping you better understand your images.
Exchangeable Image File Format (Exif) is a file format for storing metadata in digital photos. It records shooting parameters and environmental information, such as focal length, ISO, and shutter speed. PHP's Exif extension provides functions to easily process and extract this data.
Before using the Exif extension, make sure it is installed in PHP. You can check with the following command:
php -m | grep exifIf 'exif' appears in the output, the extension is installed. If not, you can install it using the steps below:
Run the following command in the terminal:
sudo apt-get install php-exifEdit the php.ini file:
sudo nano /etc/php/7.4/cli/php.iniFind the following line and uncomment it:
;extension=exifSave and exit, then restart PHP:
sudo service php7.4-fpm restartCreate a PHP script, for example exif_example.php, and place the photo in the same directory. Use the exif_read_data() function to read the photo's Exif data:
<?php
$filename = 'example.jpg'; // Photo file name
$exif_data = exif_read_data($filename, 0, true);
?>Check if the focal length exists and display it:
<?php
if (isset($exif_data['EXIF']['FocalLength'])) {
$focal_length = $exif_data['EXIF']['FocalLength'];
echo "Photo focal length: {$focal_length}mm";
} else {
echo "Could not retrieve the photo's focal length.";
}
?>After saving the script, run it in the terminal:
php exif_example.phpIf the photo contains focal length information, the output will look like:
Photo focal length: 50mmOtherwise, it will indicate that the focal length could not be retrieved.
Using PHP's Exif extension makes it easy to extract the focal length of photos, though not all photos include this information. Proper error handling should be implemented when processing images. This method allows you to quickly access photo metadata, aiding photography learning and image management.