开发者

How can I find the width of an image using PHP?

开发者 https://www.devze.com 2023-01-07 23:31 出处:网络
I was wondering 开发者_高级运维how can I find the width of an image using php.Easy, you can use getimagesize:

I was wondering 开发者_高级运维how can I find the width of an image using php.


Easy, you can use getimagesize:

list($width, $height) = getimagesize($filename);


getimagesize()


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


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.


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;
    }
    


Check here for official document

list($Img_width, $Img_height) = getimagesize('Image Path');
echo "Width: " . $Img_width. "<br />";
echo "Height: " .  $Img_height;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消