18

如何在 PHP 中获取图像(JPEG 或 PNG)的图像方向(横向或纵向)?

我创建了一个用户可以上传图片的 php 站点。在我将它们缩小到更小的尺寸之前,我想知道图像是如何定位的以便正确缩放它。

感谢您的回答!

4

6 回答 6

49

我一直这样做:

list($width, $height) = getimagesize('image.jpg');
if ($width > $height) {
    // Landscape
} else {
    // Portrait or Square
}
于 2012-11-26T16:04:08.440 回答
9
list($width, $height) = getimagesize("path/to/your/image.jpg");

if( $width > $height)
    $orientation = "landscape";
else
    $orientation = "portrait";
于 2012-11-26T16:05:32.937 回答
2

我想你可以检查图像宽度是否比横向和纵向的长度长,如果长度比宽度长。

你可以用一个简单的IF / ELSE语句来做到这一点。

您还可以使用以下功能:Imagick::getImageOrientation

http://php.net/manual/en/imagick.getimageorientation.php

于 2012-11-26T16:00:48.217 回答
0

简单的。只需检查宽度和高度并比较它们以获得方向。然后相应地调整大小。真是直截了当。如果你想保持纵横比,但适合一些方形框,你可以使用这样的东西:

public static function fit_box($box = 200, $x = 100, $y = 100)
{
  $scale = min($box / $x, $box / $y, 1);
  return array(round($x * $scale, 0), round($y * $scale, 0));
}
于 2012-11-26T16:00:34.030 回答
0

我使用了一个通用的缩小算法,比如 . ..

   function calculateSize($width, $height){

            if($width <= maxSize && $height <= maxSize){
                $ratio = 1;
            } else if ($width > maxSize){
                $ratio = maxSize/$width;
                } else{
                    $ratio = maxSize/$height;
                    }

        $thumbwidth =  ($width * $ratio);
        $thumbheight = ($height * $ratio);
        }

这里的 max size 是我为 height 和 width 初始化为 120px 的那个。. . 使缩略图不超过该大小。. ..

这适用于我,无论横向或纵向方向如何,都可以普遍应用

于 2012-11-26T16:03:38.817 回答
0

我正在使用这个速记。共享以防万一有人需要单线解决方案。

$orientation = ( $width != $height ? ( $width > $height ? 'landscape' : 'portrait' ) : 'square' );

首先它检查图像是否不是 1:1(正方形)。如果不是,则确定方向(横向/纵向)。

我希望有人觉得这很有帮助。

于 2020-05-29T10:07:07.093 回答