saoudrizwan / Disk

Easily persist structs, images, and data on iOS
MIT License
3.1k stars 170 forks source link

[macOS] Converting UIImage and [UIImage] framework files to NSImage equivalents? #36

Closed ghost closed 6 years ago

ghost commented 6 years ago

Hi. A curious question, perhaps?

I have adapted Disk to work in my macOS app project except for the UIImage framework files. I would like to cache some book cover preview images that were loaded into a collection view.

I've been looking at NSImage repos on GitHub too, and found ESSImageCategory, which allows NSImages to be written to disk in other formats other than just TIFF. It's in Objective-C, but I'll look it over and see if I can borrow ideas from the implementation of representationForFileType.

Any suggestions or help in converting the UIImage files will be awesome, thanks.

Cheers

--mike

ghost commented 6 years ago

Well, damn. That was a bit simpler than I originally thought.

After reading through a few StackOverflow posts on similar Q&As of saving NSImages to various formats in Swift, I created these two functions named similar to their iOS cousins.

static func NSImageJPEGRepresentation(_ image: NSImage?, _ comprRate: CGFloat) -> Data? {
    // Create a JPEG representation from the current image.
    let bitmap = NSBitmapImageRep(data: (image?.tiffRepresentation)!)
    return bitmap?.representation(using: .jpeg, properties: [.compressionFactor: comprRate])
  }
static func NSImagePNGRepresentation(_ image: NSImage?) -> Data? {
    // Create a PNG representation from the current image.
    let bitmap = NSBitmapImageRep(data: (image?.tiffRepresentation)!)
    return bitmap?.representation(using: .png, properties: [:])
  }

This works great, as I have just tested this by 'caching' a bunch of NSImages from a collection view in my app to a folder using Disk. I was also thinking I could put a macOS version of Disk onto my GitHub, that's if you don't mind.

I'll close this issue too, as it's not required anymore.

--mike

saoudrizwan commented 6 years ago

Hey @mike-norman, that's exactly what I would do too in this case. Disk is primarily for iOS devices, and adding macOS compatibility would overcomplicate best practices and proper directories. You could of course make a Disk-macOS-extension pod and I could add that to the README! Please keep in mind though that macOS is much more diverse and complicated when it comes to file management.