php getimagesize 获取图片宽高以及后缀
- 2019 年 12 月 17 日
- 筆記
获取文件宽高在 PHP 中有一个简单函数 getimagesize
。只需要传递文件名即可。
getimagesize ( string $filename [, array &$imageinfo ] ) : array
使用方法:
<?php $image_arr = getimagesize('https://upyun.laravelcode.cn/uploads/images/resources/201906/24/jPINglfSMseh2Ri1g9JbgIY8ykisfe6mfJJmTh5P.jpeg'); return $image_arr;
返回内容为:
{ "0": 563, "1": 1000, "2": 2, "3": "width="563" height="1000"", "bits": 8, "channels": 3, "mime": "image/jpeg" }
返回结果说明:
- 索引 0 给出的是图像宽度的像素值
- 索引 1 给出的是图像高度的像素值
- 索引 2 给出的是图像的类型,返回的是数字,其中1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM
- 索引 3 给出的是一个宽度和高度的字符串,可以直接用于 HTML 的 <image> 标签
- 索引 bits 给出的是图像的每种颜色的位数,二进制格式
- 索引 channels 给出的是图像的通道值,RGB 图像默认是 3
- 索引 mime 给出的是图像的 MIME 信息,此信息可以用来在 HTTP Content-type 头信息中发送正确的信息,如: header("Content-type: image/jpeg");
可见返回内容为数组,我们获取数组下标即可
<?php $width = $image_arr[0]; $height = $image_arr[1]; $type = $image_arr[6];
另外、我们也可以使用 list 来获取数据.
<?php list($width, $height, $type) = getimagesize('https://upyun.laravelcode.cn/uploads/images/resources/201906/24/jPINglfSMseh2Ri1g9JbgIY8ykisfe6mfJJmTh5P.jpeg'); return [ "width" => $width, 'height' => $height, 'type' => $type, ];