【VBA】画像の幅と高さを取得する

概要

Microsoft Windows Image Acquisition (WIA) Automation Layerは画像を操作するライブラリです。
VBAの参照設定を行うことでPNG画像やJPG画像の情報を取得することができます。

Microsoft Windows Image Acquisition Automation Layerの目的(Purpose)の部分を参照してみると
画像の処理用ライブラリであることが書かれてます。
https://learn.microsoft.com/ja-jp/previous-versions/windows/desktop/wiaaut/-wiaaut-startpage

The Windows Image Acquisition (WIA) Automation Layer is a full-featured image manipulation component that provides end-to-end image processing capabilities

Windows Image Acquisition (WIA) Automation Layerは、エンドツーエンドの画像処理機能を提供するフル機能の画像処理コンポーネントです。

画像情報取得する

C:\wiatestフォルダ内にpngとjpgの画像を置きました。

  • 幅100x高さ150のpng画像
  • 幅200x高さ250のjpg画像

Windows Image Acquisition Automationの機能を使用するには参照設定が必要です。
Microsoft Windows Image Acquisition Libraryにチェックをつけます。

https://kazusa-pg.com/vba-references/

ImageFileオブジェクトを使用して画像を取り込み、PNG画像とJPG画像の幅と高さをそれぞれ取得して
イミディエイトウィンドウに表示します。
https://learn.microsoft.com/ja-jp/previous-versions/windows/desktop/wiaaut/-wiaaut-imagefile

 1Option Explicit
 2
 3Sub PrintPictureInfo()
 4
 5  Dim pngImg As New ImageFile
 6  pngImg.LoadFile "C:\wiatest\100x150.png"
 7  Debug.Print "PNG画像の幅:" & pngImg.Width
 8  Debug.Print "PNG画像の高さ:" & pngImg.Height
 9  
10  Dim jpgImg As New ImageFile
11  jpgImg.LoadFile "C:\wiatest\200x250.jpg"
12  Debug.Print "JPG画像の幅:" & jpgImg.Width
13  Debug.Print "JPG画像の高さ:" & jpgImg.Height
14  
15  Set pngImg = Nothing
16  Set jpgImg = Nothing
17
18End Sub

イミディエイトウィンドウにPNG画像とJPG画像の幅と高さが出力されます。

1PNG画像の幅:100
2PNG画像の高さ:150
3JPG画像の幅:200
4JPG画像の高さ:250

画像の幅と高さをシートに記入する

Sheet1シートのA列2行以降に画像パスを記入しました。
この画像パスを元に画像の幅と高さを取得し、B列に画像の幅、C列に画像の高さを記入してみます。

 1Option Explicit
 2
 3'画像の幅と高さを保存する構造体
 4Type PictureInfo
 5  Width As Long
 6  Height As Long
 7End Type
 8
 9Function GetPictureInfo(path As String) As PictureInfo
10
11  Dim pi As PictureInfo
12  Dim img As New ImageFile
13  
14  img.LoadFile path
15  pi.Width = img.Width
16  pi.Height = img.Height
17  GetPictureInfo = pi
18  
19  Set img = Nothing
20
21End Function

GetPictureInfoを呼び出してシートに画像の幅と高さを記入してみます。

 1Sub TestGetPictureInfo()
 2
 3  Dim sht As Worksheet
 4  Set sht = ThisWorkbook.Worksheets("Sheet1")
 5  
 6  Dim pi As PictureInfo
 7  pi = GetPictureInfo(sht.Cells(2, 1))
 8  sht.Cells(2, 2) = pi.Width
 9  sht.Cells(2, 3) = pi.Height
10  
11  pi = GetPictureInfo(sht.Cells(3, 1))
12  sht.Cells(3, 2) = pi.Width
13  sht.Cells(3, 3) = pi.Height
14  
15End Sub

それぞれの画像の幅と高さがB列とC列に記入されました。

関連ページ