Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to load from NSImage? #27

Closed
ospfranco opened this issue Jul 29, 2022 · 1 comment
Closed

How to load from NSImage? #27

ospfranco opened this issue Jul 29, 2022 · 1 comment

Comments

@ospfranco
Copy link

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!

@ospfranco
Copy link
Author

ospfranco commented Jul 30, 2022

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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant