Retrieve image orientation in PHP

后端 未结 6 973
闹比i
闹比i 2021-02-04 06:54

How can I get the image orientation (landscape or portrait) of an image (JPEG or PNG) in PHP?

I created a php site where users can upload pictures. Before I scale them

相关标签:
6条回答
  • 2021-02-04 07:08

    I suppose you could check if the Image width is longer than the length for Landscape and for Portrait if the Length is longer than width.

    You can do that with a simple IF / ELSE statement.

    You could also use the function: Imagick::getImageOrientation

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

    0 讨论(0)
  • 2021-02-04 07:10

    I've always done this:

    list($width, $height) = getimagesize('image.jpg');
    if ($width > $height) {
        // Landscape
    } else {
        // Portrait or Square
    }
    
    0 讨论(0)
  • 2021-02-04 07:17
    list($width, $height) = getimagesize("path/to/your/image.jpg");
    
    if( $width > $height)
        $orientation = "landscape";
    else
        $orientation = "portrait";
    
    0 讨论(0)
  • 2021-02-04 07:22

    I am using this shorthand. Sharing just in case someone needs a one-line solution.

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

    First it checks if image is not 1:1 (square). If it is not it determines the orientation (landscape / portrait).

    I hope someone finds this helpful.

    0 讨论(0)
  • 2021-02-04 07:29

    Simple. Just check the width and height and compare them to get orientation. Then resize accordingly. Straight-forward really. If you are trying to maintain aspect ratio, but fit into some square box you could use something like this:

    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));
    }
    
    0 讨论(0)
  • 2021-02-04 07:30

    I use a generalized scaling down algorithm like . ..

       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);
            }
    

    Here max size is the one I initialized to something like 120px for both height and width . . . so that the thumbnail does not exceed that size . . ..

    This Works for me which is irrespective of landscape or portrait orientation and can be applied generally

    0 讨论(0)
提交回复
热议问题