如何确定 JPG 图像方向



需要在shell脚本中获取图像文件的高度和宽度。

我有一个返回正确图像大小的脚本,但是高度和宽度并不总是与正确的方向(纵向或横向(相关。 是否有我可以检查的属性来确定是使用 h x W 还是 W x H ?

$imgloc = 'c:pics'
$folder = 'pics'
Set-Location -Path $imgloc
$files = Get-ChildItem -Path $imgloc
$icnt = 0
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
$icnt++
$hfile = (get-item $file)
$img = [System.Drawing.Image]::Fromfile($hfile);
$ih= $img.Size.Height
$iw= $img.Size.width
$imgsize = "$iw"+"x"+"$ih"
$imgsize
}

您可以使用如下所示的内容从jpg文件中获取您似乎需要的所有属性,并根据返回值进行操作Orientation

$imgloc = 'D:'           #'# dummy comment to restore syntax highlighting in SO
# the various System.Photo.Orientation values
# See: https://learn.microsoft.com/en-us/windows/win32/properties/props-system-photo-orientation
#      https://learn.microsoft.com/en-gb/windows/win32/gdiplus/-gdiplus-constant-property-item-descriptions#propertytagorientation
$orientation = 'Unknown', 'Normal', 'FlipHorizontal', 'Rotate180', 'FlipVertical', 'Transpose', 'Rotate270', 'Transverse', 'Rotate90'
Get-ChildItem -Path $imgloc -Filter '*.jpg' | ForEach-Object {
$img = [System.Drawing.Image]::Fromfile($_.FullName)
# return the properties
$value = $img.GetPropertyItem(274).Value[0]
[PsCustomObject]@{
'Path'        = $_.FullName
'Width'       = $img.Size.width
'Height'      = $img.Size.Height
'Orientation' = $orientation[$value]
}
}

这将作为示例返回

Path         Width Height Orientation
----         ----- ------ -----------
D:test.jpg   2592   1456 Normal     
D:test2.jpg  2336   4160 Normal     
D:test3.jpg  2560   1920 Rotate270

,如果OrientationRotate270Rotate90则可以交换宽度和高度的值。

编辑

正如 JosefZ 所评论的那样,方向值也在[System.Drawing.RotateFlipType]枚举类中声明,如下所示:

Name               Value
----               -----
Rotate180FlipXY        0
RotateNoneFlipNone     0
Rotate90FlipNone       1
Rotate270FlipXY        1
Rotate180FlipNone      2
RotateNoneFlipXY       2
Rotate270FlipNone      3
Rotate90FlipXY         3
RotateNoneFlipX        4
Rotate180FlipY         4
Rotate90FlipX          5
Rotate270FlipY         5
Rotate180FlipX         6
RotateNoneFlipY        6
Rotate270FlipX         7
Rotate90FlipY          7

值范围为 0 到 7,没有一个是不同的,而您使用的值$img.GetPropertyItem(274).Value[0]范围为 1 到 8,并且与 System.Photo.Orientation 的值一致

最新更新