Working with images in VBA - Image Properties

Dan_W

Well-known Member
Joined
Jul 11, 2018
Messages
1,918
Office Version
  1. 365
Platform
  1. Windows
Reading Basic Image Properties

This is a continuation of my notes on the WIA COM Object, which start with Working with images in VBA - Displaying PNG files

WIA provides an easy way to get access to basic images properties on the one hand, and more to both read and write more advanced image properties, such as EXIF MetaData and Animated GIF frames. Below, I set out a simple routine to demonstrate how to load an image into the WIA Object, and then access the various properties. This is not intended to be exhaustive. My suggestion would be to step through the code, and check out the WIA Object in the Object Browser in the VBA IDE once the image has loaded in order to get a good understanding.

The routines set out in Part 1 demonstrate how to convert various data sources into an stdPicture object. In order to get access to the image properties, though, it is necessary to convert the data into an ImageFile - one of the three main WIA Objects used for image manipulation/display in VBA. (the other two are Vector and ImageProcess). As such, I've had to write an additional function - GetImageFileFromURL (which bears a stunning similarity to one of the Part 1 functions - GetImageFromURL); this will read an image file from a URL.

Here is a test sub with that will process two files: (1) an image on the internet (I have used this one before, because it has EXIF Metadata on it); and
(2) an animated GIF file of a dancing panda... because why not. The static image is on the right hand side for your reference. The code envisages that you download the GIF image yourself (URL in the comments) so as to demonstrate how to load an image from your local drive using the LoadFile method, but you're welcome to use another image. dancingpanda.png

VBA Code:
    Sub BasicTest()
     
        Dim File1 As Object         ' WIA.ImageFile
        Dim File2 As Variant        ' String - Filename
     
     
        Debug.Print vbCrLf & "----------------  TEST 1  -----------------" & vbCrLf
        Set File1 = GetImageFileFromURL("https://github.com/KallunWillock/JustMoreVBA/raw/main/Images/pexels-jill-evans-11567527.jpg")
        BasicImageProperties_Test File1
     
        Debug.Print vbCrLf & "----------------  TEST 2  -----------------" & vbCrLf
       ' https://tenor.com/view/hasher-happy-sticker-gif-24532177
       ' https://media.tenor.com/SaX1bE-Tug8AAAAi/hasher-happy-sticker.gif
       ' Source URL: TENOR GIF

        File2 = "D:\hasher-happy-sticker.gif"
        BasicImageProperties_Test File2
    End Sub

The following code should be placed in a standard module, and you're welcome to call it whatever you like - maybe modWorkingWithWhackyWIA or modDansDemos...:cool: or something less fun, like modWIA_Properties

VBA Code:
    Option Explicit
 
    ' WIA - accessing image properties
    '
    ' The following function (and test procedure) demonstrates
    ' how to access basic image properties with the WIA COM Object.
    ' I have used late binding here, but you can enable
    ' early-binding (and intellisense) by selecting:
    '
    ' Tools > References > Microsoft Windows Image Acquisition Library
    '
    ' Dan_W
 
    Enum ImagePropertyTypeEnum
        ImageWidth
        ImageHeight
        HorizontalResolution
        VerticalResolution
        IsAnimated
        ActiveFrame
        FrameCount
        FileExtension
        HasTransparency
        PixelDepth
    End Enum
 
    Function GetImageProperties(ByVal File As Variant, ByVal PropertyType As ImagePropertyTypeEnum)
     
        Dim TargetImage As Object
     
        If TypeName(File) = "IImageFile" Then
            Set TargetImage = File
        ElseIf TypeName(File) = "String" Then
            If Len(Dir(File)) = 0 Then Exit Function
            ' Late-binding option
            Set TargetImage = CreateObject("WIA.ImageFile")
            ' Early-binding option
            ' Dim TargetImage As New WIA.ImageFile
            TargetImage.LoadFile File
        End If
     
        With TargetImage
            GetImageProperties = Trim(Array(.Width, .Height, .HorizontalResolution, .VerticalResolution, _
                                            CBool(.IsAnimated), .ActiveFrame, .FrameCount, .FileExtension, _
                                            CBool(.IsAlphaPixelFormat), .PixelDepth)(PropertyType))
        End With
     
        Set TargetImage = Nothing
     
    End Function

 
    Sub BasicImageProperties_Test(ByVal File As Variant)
     
        Dim PropertyHeadings  As Variant
        PropertyHeadings = Array("Width (pixels)", "Height (pixels)", "Horizontal Resolution", "Vertical Resolution", _
                                 "Animated", "Active Frame", "Frame Count", "File Extension", _
                                 "Is Alpha Pixel Format", "Pixel Depth")
        Dim Counter As Long
     
        Dim Heading As String * 22
        For Counter = LBound(PropertyHeadings) To UBound(PropertyHeadings)
            Heading = PropertyHeadings(Counter)
            Debug.Print Counter + 1, Heading, GetImageProperties(File, Counter)
        Next
     
    End Sub

    Function GetImageFileFromURL(ByVal TargetURL As String) As Object
        Dim HTTP            As Object
     
        Set HTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
        HTTP.Open "GET", TargetURL, False
        HTTP.send

        If HTTP.Status = 200 Then
            With CreateObject("WIA.Vector")
                .BinaryData = HTTP.responsebody
                Set GetImageFileFromURL = .ImageFile
            End With
        End If

        Set HTTP = Nothing
    End Function
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
And if all goes to plan, you should get this output to the immediate window:


VBA Code:
----------------  TEST 1  -----------------

 1            Width (pixels)              640
 2            Height (pixels)             954
 3            Horizontal Resolution       72
 4            Vertical Resolution         72
 5            Animated                    False
 6            Active Frame                1
 7            Frame Count                 1
 8            File Extension              jpg
 9            Is Alpha Pixel Format       False
 10           Pixel Depth                 24

----------------  TEST 2  -----------------

 1            Width (pixels)              200
 2            Height (pixels)             200
 3            Horizontal Resolution       96
 4            Vertical Resolution         96
 5            Animated                    True
 6            Active Frame                1
 7            Frame Count                 22
 8            File Extension              gif
 9            Is Alpha Pixel Format       True
 10           Pixel Depth                 32

I'd say it's largely self-explanatory, but note the File Extension property - the title is thoroughly deceptive. It does not, in fact, tell you what the file extension of the image - it tells you the actual file format of the image. You can test it by manually changing the extension to BMP or something, and run that file through the routine.... I've found this to be helpful at times.
 
Upvote 0

Forum statistics

Threads
1,223,214
Messages
6,170,772
Members
452,353
Latest member
strainu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top