PHP Basics

How to calculate size of an Image using PHP?

One prime approach to implement fast loading webpage is to provide image size that is width and height data to the image tag. It will render fast. Even in Accelerated Mobile Page (AMP) implementation it is mandatory to provide image width and height inside the image tag(amp-img). That’s why we need to calculate the size of the image.

How can we calculate size of an image?

Calculate the image size

PHP has predefined function getimagesize() which calculates the size of an image file and returns in an array format.

GetImageSize()

getimagesize() php function takes the image file path as an argument.

Example

Image File: /temp/flower.png —->This is a image file.

Lets calculate the size.

<?php

$img=”/temp/flower.png”;

var_dump(getimagesize($img));

?>

 

output:

array(6) { [0]=> int(700) [1]=> int(580) [2]=> int(3) [3]=> string(24) “width=”700″ height=”580″” [“bits”]=> int(8) [“mime”]=> string(9) “image/png” }

Note: In this output, we can easily know, 0 index contains the width size, 1 index contains the height of the image, and also bits index contains the size of the image. 

Therefore using getimagesize() function we can determine the size of an image.