getimagesize()
是一個 PHP 函數,用于獲取圖像尺寸信息。要在網絡請求中使用它,您需要首先使用 cURL 或 file_get_contents() 等函數獲取圖像的原始數據,然后將其傳遞給 getimagesize()
函數。以下是兩種方法的示例:
方法 1:使用 cURL
function get_image_size_from_url($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
return getimagesize($data);
}
$url = 'https://example.com/image.jpg';
$image_size = get_image_size_from_url($url);
if ($image_size !== false) {
list($width, $height) = $image_size;
echo "Image width: $width, height: $height";
} else {
echo "Failed to get image size.";
}
方法 2:使用 file_get_contents()
function get_image_size_from_url($url) {
$data = file_get_contents($url);
return getimagesize($data);
}
$url = 'https://example.com/image.jpg';
$image_size = get_image_size_from_url($url);
if ($image_size !== false) {
list($width, $height) = $image_size;
echo "Image width: $width, height: $height";
} else {
echo "Failed to get image size.";
}
請注意,這兩種方法都需要您的 PHP 設置允許從外部 URL 下載文件。如果您的 PHP 設置不允許這樣做,您可能需要修改配置文件以允許這些操作。