Hướng dẫn
Quảng cáo

Lấy kích thước file ảnh bằng PHP?

Chủ đề: PHP / MySQLBài trước|Bài tiếp

Trả lời: dùng hàm getimagesize(), hoặc phải dùng curl

Để lấy kích thước file ảnh có 2 trường hợp:

  1. File lưu trữ trên host
  2. File remote (Lấy từ website khác)

File lưu trữ trên host

Để lấy kích thước file loại này bạn dùng hàm getimagesize(), như sau:

Ví dụ

<?php 
// Gọi hàm getimagesize()
list($width, $height, $type) = getimagesize("path/logo.png");
// Displaying dimensions of the image
echo "Chiều rộng : " . $width . "<br/>";
echo "Chiều cao : " . $height . "<br/>";
echo "Loại ảnh :" . $type ;
?>

File remote (thông tin file ảnh từ URL)

Dưới đây là code lấy thông tin file ảnh từ đường liên kết hình ảnh

Ví dụ

<?php 
function getimgsize( $url, $referer = '' ) {
    // Set headers    
    $headers = array( 'Range: bytes=0-131072' );    
    if ( !empty( $referer ) ) { array_push( $headers, 'Referer: ' . $referer ); }
  // Get remote image
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
  $data = curl_exec( $ch );
  $http_status = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
  $curl_errno = curl_errno( $ch );
  curl_close( $ch );
  // Get network stauts
  if ( $http_status != 200 ) {
    echo 'HTTP Status[' . $http_status . '] Errno [' . $curl_errno . ']';
    return [0,0];
  }
  // Process image
  $image = imagecreatefromstring( $data );
  $dims = [ imagesx( $image ), imagesy( $image ) ];
  imagedestroy($image);
  return $dims;
}
// Set image url
$url = '';
// Get image dimensions
list( $width, $heigth) = getimgsize( $url );
echo $width.' x '.$heigth;
?>

Câu hỏi liên quan

Dưới đây là một số câu hỏi thường gặp khác liên quan đến chủ đề này:

Advertisements