这相当棘手。您从.Width
and.Height
属性收到的尺寸实际上是OLE_YSIZE_HMETRIC
/ OLE_XSIZE_HMETRIC
,据我所知,它是代表 0.01mm 的测量增量。
我最初没有看到任何简单的解决方法,(公式或至少是一个有用的 WinAPI 函数)。
这应该适用于大多数具有正常/默认屏幕分辨率设置的用户
函数使用后期绑定/不需要对 Publisher 的引用,尽管该库仍然需要在用户的机器上可用。
Option Explicit
Sub Test()
Dim filepath$
filePath = "C:\image_file.JPG"
MsgBox "Height = " & GetImageDimensions(filepath)(0) & vbNewLine & _
"Width = " & GetImageDimensions(filepath)(1), vbOKOnly, "Dimensions"
End Sub
Function GetImageDimensions(filepath) As Variant
'Function returns an array of (Height, Width) from a specific image file path
'
Dim tmp(0 To 1) As Long
Dim oPub As Object
Set oPub = CreateObject("Publisher.Application")
'returning picture.width in OLE_YSIZE_HIMETRIC/OLE_XSIZE_HIMETRIC
' these are representing 0.01 mm
With LoadPicture(filepath)
'Multiply by 0.01 to get dimension in millimeters, then
' use the MS Publisher functions to convert millimeters -> points -> pixels
tmp(0) = 0.01 * oPub.PointsToPixels(oPub.MillimetersToPoints(.Height))
tmp(1) = 0.01 * oPub.PointsToPixels(oPub.MillimetersToPoints(.Width))
End With
GetImageDimensions = tmp
End Function
这是一个测试用例:
结果如下:
评论更新
调试时我得到以下尺寸:
.Height
= 3493
.Width
= 8943
但是,您表示您分别得到 2794 和 7154。
当我更改屏幕分辨率(例如,125%)时,我可以复制您的结果。下面的方法应该可以解决这种差异。
尝试使用 WinAPI 来(希望)解释我们得到的任何差异(像素大小,可能在您的计算机上有所不同,这可能会导致这种情况,尽管我希望 Publisher 函数会解释这一点......)
无论分辨率如何,这个带有 WinAPI 调用的函数都应该适用于所有用户
Function GetImageDimensions2(filePath As String) As Variant
'Function returns an array of (Height, Width) from a specific image file path
Dim tmp(0 To 1) As Long
'returning picture.width in OLE_YSIZE_HIMETRIC/OLE_XSIZE_HIMETRIC
' these are representing 0.01 mm
With LoadPicture(filePath)
tmp(0) = .Height / 2540 * (1440 / TwipsPerPixelY())
tmp(1) = .Width / 2540 * (1440 / TwipsPerPixelX())
End With
GetImageDimensions2 = tmp
End Function
并将这些 WinAPI 调用包含在另一个模块中:
Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, _
ByVal hdc As Long) As Long
Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, _
ByVal nIndex As Long) As Long
Const HWND_DESKTOP As Long = 0
Const LOGPIXELSX As Long = 88
Const LOGPIXELSY As Long = 90
'--------------------------------------------------
Function TwipsPerPixelX() As Single
'--------------------------------------------------
'Returns the width of a pixel, in twips.
'--------------------------------------------------
Dim lngDC As Long
lngDC = GetDC(HWND_DESKTOP)
TwipsPerPixelX = 1440& / GetDeviceCaps(lngDC, LOGPIXELSX)
ReleaseDC HWND_DESKTOP, lngDC
End Function
'--------------------------------------------------
Function TwipsPerPixelY() As Single
'--------------------------------------------------
'Returns the height of a pixel, in twips.
'--------------------------------------------------
Dim lngDC As Long
lngDC = GetDC(HWND_DESKTOP)
TwipsPerPixelY = 1440& / GetDeviceCaps(lngDC, LOGPIXELSY)
ReleaseDC HWND_DESKTOP, lngDC
End Function