如何在 PHP 中获取图像(JPEG 或 PNG)的图像方向(横向或纵向)?
我创建了一个用户可以上传图片的 php 站点。在我将它们缩小到更小的尺寸之前,我想知道图像的方向是如何正确缩放的。
谢谢您的回答!
我一直这样做:
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";
我想您可以检查图像宽度是否长于风景的长度,如果长度长于宽度,则检查肖像的长度。
你可以用一个简单的
IF / ELSE
语句来做到这一点。
您还可以使用以下功能:
Imagick::getImageOrientation
我正在使用这个速记。分享以防万一有人需要一个在线解决方案。
$orientation = ( $width != $height ? ( $width > $height ? 'landscape' : 'portrait' ) : 'square' );
首先检查图像是否不是 1:1(正方形)。如果不是,则确定方向(横向/纵向)。
我希望有人觉得这有帮助。
简单。只需检查宽度和高度并比较它们以获得方向。然后相应地调整大小。真的很直截了当。如果你想保持宽高比,但适合一些方框,你可以使用这样的东西:
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));
}
我使用像 . 这样的广义缩小算法。 ..
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);
}
这里的最大尺寸是我为 height 和 width 初始化为 120px 之类的东西。 . .这样缩略图就不会超过那个大小。 . ..
This Works for me 无论横向或纵向方向,都可以普遍应用
您可能需要先相对旋转图像以更正 exif 数据 - 当使用“getimagesize()”宽度/高度检查时 - 因为在某些情况下宽度高度可能会反转,具体取决于所使用的相机或设备。
$rotate = false;
$exif = exif_read_data($source_image);
if($exif['Orientation'] == '6'){
$degrees = 270;
$rotate = true;
}
if($exif['Orientation'] == '8'){
$degrees = 90;
$rotate = true;
}
if($exif['Orientation'] == '3'){
$degrees = 180;
$rotate = true;
}
// Now rotate
if($rotate){
$source_image_string = imagecreatefromjpeg($source_image) or die('Error opening file to rotate '.$source_image);
$source_image_rotated = imagerotate($source_image_string, $degrees, 0) or die('Error rotating file '.$source_image);
$rotated_image_saved = imagejpeg($source_image_rotated, $source_image) or die('Error saving rotated file '.$source_image);// Save Rotated
}
list($width, $height) = getimagesize($source_image);
if ($width > $height) {
// Landscape
} else {
// Portrait or Square
}