0

I am building a cross-platform app using SwiftUI. I have a Data object grabbed from a SwiftUI PhotosPicker and I want to reduce the file size; however, I want to do this without the use of UIKit since it is only available for iOS/iPadOS.

Is there a cross-platform solution, or do I need to handle separate cases for os(iOS) and os(macOS)?

1 Answers1

1

iOS and Mac OS both use Core Graphics under the covers. Take a look at the Core Graphics framework. It does the heavy lifting for both UIImage and NSImage, and a lot of the work for screen drawing of views.

See this thread for some examples:

Saving CGImageRef to a png file?

That code uses the Core Image function CGImageDestinationCreateWithData(). Be aware that Core Graphics is built on Core foundation (CF) objects, and it is fussy to use.

It looks like you could also convert your CGImage to a CIImage and use easier-to-use CoreImage functions to save your image to disk as a PNG or JPEG. (See the answer in that thread from August 2022 from YourMJK)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks for the direction. Instinct tells me it's probably better to simply use UIImage/NSImage and have separate code based on platform; after all, I think people have already come up with usable/tested solutions for those. In the meantime, will leave the question open in case someone can link a full cross-platform solution. Resizing image data seems like a pretty standard operation, so not sure why all the complexity... –  Apr 03 '23 at 19:42
  • 1
    Modern OS's are incredibly complex, with lots of layers. UIKit (and to a lesser extent AppKit) provide simplified interfaces that let you do a lot without having to worry about the underlying complexity, but that complexity still exists. If you stray far enough off the beaten path, you end up having to dive to the lower levels and deal with that complexity. For your case you might be right that 2 custom implementations using higher level OS frameworks is easier. – Duncan C Apr 03 '23 at 19:50
  • Note that asking for links to 3rd party libraries is not encouraged on this site. – Duncan C Apr 04 '23 at 02:10
  • Ideally it should not be a 3rd party library and just be solution written in swift code. I don't want to use any 3rd party library in my codebase unless I have to. –  Apr 04 '23 at 16:09