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
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
I've always done this:
list($width, $height) = getimagesize('image.jpg');
if ($width > $height) {
// Landscape
} else {
// Portrait or Square
}
list($width, $height) = getimagesize("path/to/your/image.jpg");
if( $width > $height)
$orientation = "landscape";
else
$orientation = "portrait";
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.
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));
}
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