VBA – WIA – Rotate an Image

I was recently exploring automating WIA because I wanted to help someone out in a forum and wanted to see what else it could. It is actually quite impressive and versatile . Below is a very simple function I put together to rotate an image which can be configured to use either Early or Late Binding WIA, so the choice is yours. This simple function now empowers us to be able to integrate image manipulations such as rotation within any Access solution (Word, Excel, PowerPoint,… any VBA solution in fact. Actually, this can even be utilized in VBScript)!

'---------------------------------------------------------------------------------------
' Procedure : WIA_RotateImage
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Roate an image by a designated number of degrees using WIA
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Late Binding version  -> None required
'             Early Binding version -> Microsoft Windows Image Acquisition Library vX.X
'
' Windows Image Acquisition (WIA)
'             https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInitialImage : Fully qualified path and filename of the original image to rotate
' lRotAng       : Number of degree to rotate the image by
'                   Appears to only support increments of 90deg.
'                   Acceptable values are: 90, 180 or 270
' sOutputImage  : Fully qualified path and filename of where to save the new image
'                   If omitted, overwrites the original file (sInitialImage)
'
' Usage:
' ~~~~~~
' Call WIA_RotateImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", _
'                      90,
'                      "C:\Users\MyUser\Desktop\Chrysanthemum_small.jpg")
'
' Call WIA_RotateImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", _
'                      90)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2017-01-18              Initial Release
' 2         2018-09-20              Updated Copyright
' 3         2022-02-25              Added Early/Late Binding Conditonal Compilation
'                                   Made sOutputImage optional to allow overwriting
'                                       the original image
' 4         2022-12-16              Updated header to add more info and fix typos
'---------------------------------------------------------------------------------------
Public Function WIA_RotateImage(sInitialImage As String, _
                                lRotAng As Long, _
                                Optional sOutputImage As String) As Boolean
    On Error GoTo Error_Handler
    #Const WIA_EarlyBind = False    'True => Early Binding / False => Late Binding
    #If WIA_EarlyBind = True Then
        Dim oIF               As WIA.ImageFile
        Dim oIP               As WIA.ImageProcess

        Set oIF = New WIA.ImageFile
        Set oIP = New WIA.ImageProcess
    #Else
        Dim oIF               As Object
        Dim oIP               As Object

        Set oIF = CreateObject("WIA.ImageFile")
        Set oIP = CreateObject("WIA.ImageProcess")
    #End If

    Set oIF = CreateObject("WIA.ImageFile")
    Set oIP = CreateObject("WIA.ImageProcess")

    oIP.Filters.Add oIP.FilterInfos("RotateFlip").FilterID
    oIP.Filters(1).Properties("RotationAngle") = lRotAng

    oIF.LoadFile sInitialImage
    Set oIF = oIP.Apply(oIF)
    If sOutputImage <> "" Then    'New file specified
        If Len(Dir(sOutputImage)) > 0 Then Kill sOutputImage
        oIF.SaveFile sOutputImage
    Else    'Overwrite original if no Dest. file specified
        Kill sInitialImage
        oIF.SaveFile sInitialImage
    End If
    WIA_RotateImage = True

Error_Handler_Exit:
    On Error Resume Next
    If Not oIP Is Nothing Then Set oIP = Nothing
    If Not oIF Is Nothing Then Set oIF = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: WIA_RotateImage" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Usage

As per the Usage section in the procedure header, there are 2 basic calls that can be made to this function.

Creating a New File

If you want to apply a rotation to an image file and then save it under a new location and/or name, you do something like:

Call WIA_RotateImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", 90, "C:\Users\MyUser\Desktop\Chrysanthemum_small.jpg")

Overwriting the Existing File

On the other hand, if you want to apply a rotation the image and save it to the original file, then you’d do something along the lines of:

Call WIA_RotateImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", 90)

Be sure this is what you want to do, as once the file is overwritten, there is no way to undo the change. The original file is permanently replaced/gone.

A Few Resources on the Subject

14 responses on “VBA – WIA – Rotate an Image

  1. Flap Zappa

    perfect solution.
    I added a form to choose the rotation left or right with some option buttons for 90, 180 and free degrees and it works great

  2. Flap Zappa

    It only seems to work with 90, 180 or 270 degrees
    If I set it to say 5 degrees
    it returns an error
    -2147024809
    error source WIA_rotateimage
    Error description: The Parameter is incorrect

  3. Sion Gwenallt

    This is fantastic. I’ve struggled with the “.chart export” method of doing this and found that this caused unexpected results as the code was executed faster than the the system could rotate the large images. Issues
    ranged from empty image files to just no change. The “.chart” method is a hack that has cost me 12 hours trying to get it to work by using delays and “distracting” the code whilst the system catches up. . The above code works great for fixing image orientation form portrait to landscape and vice versa. This should be your go to solution. Great work. Thank you.

  4. fernando

    Perfectly work. Thanks alot. By the way, how is if I want overwrite the same filename while rotate. Kindly advise

        1. fernando

          Hello Mr. Daniel, Is there a way to flip vertical or flip horizontal like mirroring from the file? Kindly advise

  5. Jay Learman

    Hello,

    I have a database full of attached files that a jpg images. Before pictures which are have the correct orientation and after pictures which do not. The are off by 90 degrees. I tried to use your code and I couldn’t figure it out. Where do insert it? I tried under Visual basic, insert module. I cut and passed it in, and tried to run it, but nothing worked. It doesn’t show up when I try to run it. How do I call it or use it? Sorry This is probably a dumb question. Thank you.

    1. Daniel Pineault Post author

      You create a new Module (standard) and then copy/paste the code. At this point performing a compile is always a good idea to ensure there are no issue with the VBA code throughout your project. Then you can call it as you see fit, using a button click event perhaps, or a form’s current event, … the choice is yours. Simply follow the usage examples in the function header. It hard to tell you more as I don’t know your setup, fields, form, …