9

I was wondering how can I find the width of an image using php.

fad
  • 91
  • 1
  • 2

7 Answers7

12

Easy, you can use getimagesize:

list($width, $height) = getimagesize($filename);
igorw
  • 27,759
  • 5
  • 78
  • 90
4

getimagesize()

quantumSoup
  • 27,197
  • 9
  • 43
  • 57
2

Use the GD libraries imagesx function, take a look at the manual page here.

Will A
  • 24,780
  • 5
  • 50
  • 61
1

You can try with this code, you can see more in www.php.net

To a file:

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

To URL:

<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

Only you have to give an output to variable.

Josh Ruiz
  • 19
  • 2
0

In addition to getimagesize() you can get the dimensions from an image resource using imagesx() and imagesy().

  1. First of all you will have to download the image data using for example file_get_contents()

  2. Then you create the image resource using imagecreatefromstring()

  3. Finally get the image width with imagesx() and the image height with imagesy().

    function get_image_dimensions($img_url=""){
    
            $image_dimensions=array();
            $image_dimensions['w']=0;
            $image_dimensions['h']=0;
    
            if($image_data=custom_file_get_contents($img_url)){
    
                $image_resource = imagecreatefromstring($image_data);
                $image_dimensions['w']=imagesx($image_resource);
                $image_dimensions['h']=imagesy($image_resource);
                imagedestroy($image_resource);
            }
    
            return $image_dimensions;
    }
    
jooas
  • 117
  • 1
  • 9
RafaSashi
  • 16,483
  • 8
  • 84
  • 94
0

Check here for official document

list($Img_width, $Img_height) = getimagesize('Image Path');
echo "Width: " . $Img_width. "<br />";
echo "Height: " .  $Img_height;
Vishal P Gothi
  • 987
  • 5
  • 15
0

As of PHP 7.1 you can do:

[0 => $width, 1 => $height, 'mime' => $mime] = getimagesize($filename);

This eliminates the need to turn $type into mime-type, while retaining the elegant array style list() assignments.

Szabolcs Páll
  • 1,402
  • 6
  • 25
  • 31