How to extract the individual sub images from an heic image

I need to be able to load an heic image and extract and output all of the sub images as pngs similar to how preview does it. For example, if you open a dynamic heic wallpaper in preview, it shows all the images in the sidebar with their names.

How do you do this? I've tried to use NSImage like below. But that only outputs a single image:

Code Block swift
let image = NSImage(byReferencing: url)
image.writePNG(toURL: newUrl)



Answered by FrankSchlegel in 660227022
I'm not sure if you are able to access sub-images using NSImage. However, you should be able to do so with a CGImageSource:
Code Block swift
let source = CGImageSourceCreateWithURL(newURL, nil)
let numSubImages = CGImageSourceGetCount(source)
for i in 0..<numSubImages {
let subImage = CGImageSourceCreateImageAtIndex(source, i, nil)
// subImage is a CGImage, you can convert it to an NSImage if you prefer:
let nsImage = NSImage(cgImage: subImage, size: NSZeroSize)
// handle image...
}


Accepted Answer
I'm not sure if you are able to access sub-images using NSImage. However, you should be able to do so with a CGImageSource:
Code Block swift
let source = CGImageSourceCreateWithURL(newURL, nil)
let numSubImages = CGImageSourceGetCount(source)
for i in 0..<numSubImages {
let subImage = CGImageSourceCreateImageAtIndex(source, i, nil)
// subImage is a CGImage, you can convert it to an NSImage if you prefer:
let nsImage = NSImage(cgImage: subImage, size: NSZeroSize)
// handle image...
}


How to extract the individual sub images from an heic image
 
 
Q