温馨提示×

php getimagesize在网络请求中怎么用

PHP
小樊
84
2024-11-20 19:46:05
栏目: 编程语言
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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 设置不允许这样做,您可能需要修改配置文件以允许这些操作。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:opcode php 在网络传输中咋用

0