Another easy to do exercise with PHP is getting an image width, height and size.
Getting the image width and height in pixels is done with the function getimagesize(). All that needs defining is the image file or link. Note that getimagesize() downloads the image so bigger image files will take noticeable time.
$image_link = 'imagefile.jpg'; $image_details = getimagesize($image_link); $width = $image_details[0]; $height = $image_details[1]; echo "$width x $height";
The above PHP code will echo out the width x height for the image specified.
To get the image file size, PHP’s function filesize() is used. As you would expect by the functions name it returns the file size in bytes.
These bytes can be formatted for readability using a function with thanks to Adnan at StackOverflow:
function format_bytes($bytes)//@Adnan StackOverflow { if ($bytes >= 1073741824) { $bytes = number_format($bytes / 1073741824, 2) . ' GB'; } elseif ($bytes >= 1048576) { $bytes = number_format($bytes / 1048576, 2) . ' MB'; } elseif ($bytes >= 1024) { $bytes = number_format($bytes / 1024, 2) . ' KB'; } elseif ($bytes > 1) { $bytes = $bytes . ' bytes'; } elseif ($bytes == 1) { $bytes = $bytes . ' byte'; } else { $bytes = '0 bytes'; } return $bytes; } $size_formatted = format_bytes(filesize($image_link));
This will output something like 1.4 MB or 612 KB etc depending on your image size of course.
Finally to avoid the main error that no image is found at the link, wrap it in a check for valid image:
if (@getimagesize($image_link)) { //Image exists } else { //Does NOT exist }
$image_link = 'Bridge.jpg'; if (@getimagesize($image_link)) { $image_details = getimagesize($image_link); $width = $image_details[0]; $height = $image_details[1]; $size_formatted = format_bytes(filesize($image_link)); echo "$width x $height $size_formatted"; } else {//Does NOT exist echo "Check your link as no image was found"; }