从URL获取图像文件尺寸

时间:2018-12-01 22:18:54

标签: excel vba excel-vba dimensions

我有此链接: https://s23527.pcdn.co/wp-content/uploads/2017/04/wine_speedlights_kit_lens.jpg.optimal.jpg

它在单元格A2上: Before

我要在Cell B2上获取此JPG URL的尺寸 After

(我不介意如何获取它,在单元格B2上可以是1920,在单元格C2上可以是1080)

1 个答案:

答案 0 :(得分:5)

您需要对URLDownloadToFile进行API调用才能下载图像。在下面的示例中,我们将下载到临时文件夹C:\Temp\

下载图像后,您将创建一个新的Shell对象,并最终使用.ExtendedProperty()属性来获取文件尺寸

下载完文件后,可以继续使用Kill()删除临时文件。

  

以下方法使用早期绑定。您将需要设置对

的引用      
Microsoft Shell Controls And Automation
     

通过在VBE菜单中转到Tools -> References

Option Explicit

#If VBA7 Then
    Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
            (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
            ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#Else
    Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
            (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
            ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If

Sub test()

    Const tmpDir$ = "C:\Temp\"
    Const tmpFile$ = "tmpPicFile.jpg"

    Debug.Print URLDownloadToFile(0, ActiveSheet.Range("A2").Value, tmpDir & tmpFile, 0, 0)
    ActiveSheet.Range("B2").Value = getFileDimensions(tmpDir, tmpFile)
    Kill tmpDir & tmpFile

End Sub

Private Function getFileDimensions(filePath$, fileName$) As String

    With New Shell32.Shell
        With .Namespace(filePath).ParseName(fileName)
            getFileDimensions = .ExtendedProperty("Dimensions")
        End With
    End With

End Function