Getting image information without loading entire image

Mac OSX specific forum
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Getting image information without loading entire image

Post by wilbert »

A fast way to check image dimensions on OSX without loading the entire image.

Code: Select all

; PB 5.40+

Structure ImageInfo
  width.l
  height.l
EndStructure

ImportC ""
  CGImageSourceCreateWithURL(url, options)
  CGImageSourceCopyPropertiesAtIndex(isrc, index, options)
EndImport

Global kCGImagePropertyPixelWidth = PeekI(dlsym_(#RTLD_DEFAULT, "kCGImagePropertyPixelWidth"))
Global kCGImagePropertyPixelHeight = PeekI(dlsym_(#RTLD_DEFAULT, "kCGImagePropertyPixelHeight"))

Procedure ImageInfo(Filename.s, *Info.ImageInfo)
  Protected isrc, dict
  If *Info
    isrc = CGImageSourceCreateWithURL(CocoaMessage(0, 0, "NSURL fileURLWithPath:$", @Filename), #Null)
    If isrc
      dict = CGImageSourceCopyPropertiesAtIndex(isrc, 0, 0)
      CFRelease_(isrc)
      CFNumberGetValue_(CFDictionaryGetValue_(dict, kCGImagePropertyPixelWidth), #kCFNumberLongType, @*Info\width)
      CFNumberGetValue_(CFDictionaryGetValue_(dict, kCGImagePropertyPixelHeight), #kCFNumberLongType, @*Info\height)
      CFRelease_(dict)
      ProcedureReturn #True
    EndIf
  EndIf
  ProcedureReturn #False
EndProcedure



; Test

If ImageInfo("MyFile.jpg", @Info.ImageInfo)
  Debug Info\width
  Debug Info\height
EndIf
Windows (x64)
Raspberry Pi OS (Arm64)