Reputation: 892
I have a function to import images from an array of NSItemProvider (passed from a PHPickerViewController) and I need to maintain transparency in the images. Any images in PNG format are correctly maintaining transparency but WebP images are not. The image import code is as follows:
private func save(itemProviders: [NSItemProvider]) async throws -> Int {
return try await withCheckedThrowingContinuation({ continuation in
let group = DispatchGroup()
var failureCount = 0
for item in itemProviders {
// webp format image
if item.hasItemConformingToTypeIdentifier(UTType.webP.identifier) {
group.enter()
item.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) { data, error in
defer {
group.leave()
}
guard let data, let image = UIImage(data: data) else {
return
}
self.saveImage(image)
}
}
else if item.canLoadObject(ofClass: UIImage.self) {
// other image formats, including PNG
group.enter()
item.loadObject(ofClass: UIImage.self) { (image, error) in
defer {
group.leave()
}
guard let image = image as? UIImage else {
return
}
self.saveImage(image)
}
}
else {
failureCount += 1
}
}
group.notify(queue: .main) {
continuation.resume(returning: failureCount)
}
})
}
Please note that the saveImage
function is a simple resize and save to disk function, and I have been able to verify that transparency is not being lost during that step.
It seems as though transparency is being lost during the call to item.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier)
or when the resulting Data
is used to instantiate a UIImage
. The code in the WebP handling block seems to be irreducibly simple though so I'm not sure how I can possibly fix this issue.
Upvotes: 1
Views: 722