|
- Option Explicit
- Private Type ImageFileHeader
- ByteOrder As Integer
- Version As Integer
- Offset(3) As Byte
- End Type
- Private Type ImageFileDictionary
- Identifier(1) As Byte
- FieldType(1) As Byte
- Count(3) As Byte
- ValueOffset(3) As Byte
- End Type
- Private Type TiffDimension
- Width As Long
- Height As Long
- End Type
- Function GetTiffDimension(tiffFile As String) As TiffDimension '主函数,根据tif文件名返回图像尺寸
- Dim iFreeFile As Integer
- Dim ifh As ImageFileHeader
- Dim ifd() As ImageFileDictionary
- Dim bLittleEndian As Boolean
- Dim arrBuffer(1) As Byte
- Dim iIFHcount As Integer
- Dim i As Integer
-
- Dim lOffset As Long
-
- iFreeFile = FreeFile
- Open tiffFile For Binary As iFreeFile
- Get #iFreeFile, 1, ifh
- If ifh.ByteOrder = &H4949 Then '"II" = LittleEndian
- bLittleEndian = True
- ElseIf ifh.ByteOrder = &H4D4D Then '"MM" = BigEndian
- bLittleEndian = False
- Else
- MsgBox "invalid TIFF format"
- Exit Function
- End If
-
- lOffset = BytesToLong(ifh.Offset, bLittleEndian)
- Get iFreeFile, lOffset + 1, arrBuffer
- iIFHcount = BytesToUInt(arrBuffer, bLittleEndian)
- ReDim ifd(iIFHcount - 1)
- Get iFreeFile, lOffset + 3, ifd
- For i = 0 To iIFHcount - 1
- If BytesToUInt(ifd(i).Identifier, bLittleEndian) = &H100 Then 'image Width
- If BytesToUInt(ifd(i).FieldType, bLittleEndian) = 3 Then '3=Int类型
- GetTiffDimension.Width = BytesToUInt(ifd(i).ValueOffset, bLittleEndian)
- ElseIf BytesToUInt(ifd(i).FieldType, bLittleEndian) = 4 Then '4=Long类型
- GetTiffDimension.Width = BytesToLong(ifd(i).ValueOffset, bLittleEndian)
- End If
- ElseIf BytesToUInt(ifd(i).Identifier, bLittleEndian) = &H101 Then 'image Height
- If BytesToUInt(ifd(i).FieldType, bLittleEndian) = 3 Then
- GetTiffDimension.Height = BytesToUInt(ifd(i).ValueOffset, bLittleEndian)
- ElseIf BytesToUInt(ifd(i).FieldType, bLittleEndian) = 4 Then
- GetTiffDimension.Height = BytesToLong(ifd(i).ValueOffset, bLittleEndian)
- End If
- End If
- Next
-
- Close iFreeFile
-
- End Function
- Function BytesToUInt(b() As Byte, Optional LittleEndian As Boolean = True) As Long 'VBA中没有Unsigned Int数据类型,所以用Long作返回值,避免出生溢出错误
- If LittleEndian Then
- BytesToUInt = CLng(b(1)) * &H100 + b(0)
- Else
- BytesToUInt = CLng(b(0)) * &H100 + b(1)
- End If
- End Function
- Function BytesToLong(b() As Byte, Optional LittleEndian As Boolean = True) As Long
- If LittleEndian Then
- BytesToLong = CLng(b(3)) * &H1000000 + b(2) * &H10000 + b(1) * &H100 + b(0)
- Else
- BytesToLong = CLng(b(0)) * &H1000000 + b(1) * &H10000 + b(2) * &H100 + b(3)
- End If
- End Function
- Sub GetDimension() '测试代码
- Dim gfd As TiffDimension
- Dim sFileName As String
- Dim iRow As Integer
- sFileName = Application.GetOpenFilename("tif格式图片(*.tif),*.tif", , "请选择要查看的tif文件")
- If sFileName = "False" Then Exit Sub
- gfd = GetTiffDimension(sFileName)
- iRow = Sheet1.Range("a65536").End(xlUp).Row + 1
- Sheet1.Cells(iRow, 1) = sFileName
- Sheet1.Cells(iRow, 2) = gfd.Width
- Sheet1.Cells(iRow, 3) = gfd.Height
- End Sub
复制代码 |
|