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,  ];