Skip to content

判断图片是正方形还是长方形

要判断一张图片是正方形(宽高相等)还是长方形(宽高不等),可以使用 PHP 的 GD 库或 Imagick 扩展来获取图片的尺寸信息,然后进行比较。

使用 GD 库的方法

php
function checkImageShape($imagePath) {
    // 获取图片尺寸信息
    list($width, $height) = getimagesize($imagePath);
    
    if ($width === $height) {
        return "正方形 (${width}×${height})";
    } else {
        return $width > $height 
            ? "横向长方形 (${width}×${height})" 
            : "纵向长方形 (${width}×${height})";
    }
}

// 使用示例
$imagePath = 'example.jpg';
$result = checkImageShape($imagePath);
echo $result;

使用 Imagick 扩展的方法

php
function checkImageShapeWithImagick($imagePath) {
    try {
        $image = new Imagick($imagePath);
        $width = $image->getImageWidth();
        $height = $image->getImageHeight();
        
        if ($width === $height) {
            return "正方形 (${width}×${height})";
        } else {
            return $width > $height 
                ? "横向长方形 (${width}×${height})" 
                : "纵向长方形 (${width}×${height})";
        }
    } catch (Exception $e) {
        return "无法读取图片: " . $e->getMessage();
    }
}

// 使用示例
$imagePath = 'example.jpg';
$result = checkImageShapeWithImagick($imagePath);
echo $result;

注意事项

  1. 确保服务器已安装 GD 库或 Imagick 扩展
  2. 检查文件是否存在并有读取权限
  3. 对于远程图片,可能需要先下载到本地或使用其他方法获取尺寸

扩展功能

你还可以添加容差判断,比如允许宽高有微小差异时仍认为是正方形:

php
function checkImageShapeWithTolerance($imagePath, $tolerance = 5) {
    list($width, $height) = getimagesize($imagePath);
    
    if (abs($width - $height) <= $tolerance) {
        return "近似正方形 (${width}×${height})";
    } else {
        return $width > $height 
            ? "横向长方形 (${width}×${height})" 
            : "纵向长方形 (${width}×${height})";
    }
}

以上代码可以根据你的具体需求进行调整。

Binstork