blog
blog copied to clipboard
How to convert NSImage to PNG Data
Create NSBitmapImageRep
with preferred size and draw
NSImage
onto that.
Need to construct NSBitmapImageRep
specifically instead of using convenient initializers like NSBitmapImageRep(data:)
, NSBitmapImageRep(cgImage:)
to avoid device dependant resolution issue.
extension NSImage {
func pngData(
size: CGSize,
imageInterpolation: NSImageInterpolation = .high
) -> Data? {
guard let bitmap = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: .deviceRGB,
bitmapFormat: [],
bytesPerRow: 0,
bitsPerPixel: 0
) else {
return nil
}
bitmap.size = size
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
NSGraphicsContext.current?.imageInterpolation = imageInterpolation
draw(
in: NSRect(origin: .zero, size: size),
from: .zero,
operation: .copy,
fraction: 1.0
)
NSGraphicsContext.restoreGraphicsState()
return bitmap.representation(using: .png, properties: [:])
}
}
Read more
- https://stackoverflow.com/questions/17507170/how-to-save-png-file-from-nsimage-retina-issues