获取图像高度和宽度作为整数值?


98

我尝试使用PHP函数getimagesize,但无法将图像的宽度和高度提取为整数值。

我该如何实现?

Answers:


197

尝试这样:

list($width, $height) = getimagesize('path_to_image');

确保:

  1. 您在此处指定正确的图像路径
  2. 图像具有读取权限
  3. chmod图像目录到755

另外,请尝试在路径前面加上前缀$_SERVER["DOCUMENT_ROOT"],这有时在您无法读取文件时会有所帮助。


2
不需要目录上的777。

@poke:您真的100%确定吗?
Sarfraz

5
是。777表示对所有者,组和所有人的读取,写入和执行权限。您需要具有读取和执行权限才能访问目录,但不需要写入权限。而且您也不需要所有人都拥有这种权利。对于不需要在目录内创建文件的每次访问,755应该都不错。

1
对我来说有趣的是,您需要目录的执行权限,而不是映像本身的权限(与644上的映像配合使用)。
李撒克逊人

1
您需要打开allow_url_fopen才能getimagesize()在远程图像上使用。
VertigoRay

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

要么,

$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];

13

getimagesize()返回包含图像属性的数组。

list($width, $height) = getimagesize("path/to/image.jpg");

只是获得宽度和高度或

list($width, $height, $type, $attr)

以获得更多信息。


7

像这样 :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

不起作用:getimagesize() expects parameter 1 to be string, resource given,函数getimagesize需要文件名
lopisan

6

PHP的getimagesize()返回数据数组。数组中的前两项是您感兴趣的两项:宽度和高度。要获得这些,您只需在返回的数组中请求前两个索引:

var $imagedata = getimagesize("someimage.jpg");

print "Image width  is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];

有关更多信息,请参见文档


3

getimagesize('image.jpg') 该函数仅allow_url_fopen在服务器上的php.ini文件中设置为1或On 时才起作用,如果未启用,则应在使用 ini_set('allow_url_fopen',1); getimagesize()函数的文件顶部使用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.