tayloraswift / swift-png

decode, inspect, edit, and encode png images in pure swift

Home Page:https://swiftinit.org/docs/swift-png

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to load from NSImage?

ospfranco opened this issue · comments

First of all, thanks for the library! I have loaded my image into an NSImage (I use the native APIs to do some manipulations) afterwards instead of saving it to a file, I would like to pass the in-memory data directly to swift-png to save it already compressed. Could you give me a hand and detail what is necessary to achieve this? I would greatly appreciate it!

I managed to get it working, (using the Blob struct from the documentation):

let pngRep = NSBitmapImageRep(cgImage: tempImage!.cgImage!)
let pngData = pngRep.representation(using: .png, properties: [:])

let array = imageData!.withUnsafeBytes {
  [UInt8](UnsafeBufferPointer(start: $0, count: imageData!.count))
}
let image:PNG.Data.Rectangular  = try .decompress(stream: &blob)

blob = .init([])
try image.compress(stream: &blob, level: 12)

guard let _:Void = (System.File.Destination.open(path: targetURL.path) {
  guard let _:Void = $0.write(blob.data) else {
    print("Failed to write to file")
    fatalError("failed to write to file '\(targetURL.path)'")
  }
}) else {
  print("ROPO Failed to open file!")
  fatalError("failed to open file '\(targetURL.path)'")
}

print("Image saved!")

The only problem I'm facing right now is that the image is actually bigger than the original...