如何将 NSImage 转换为 PNG
2022-09-12 本文已影响0人
Swift社区
首先创建 NSBitmapImageRep 尺寸,并在上面绘制 NSImage。NSBitmapImageRep 需要专门构建,不是直接使用 NSBitmapImageRep(data:) 初始化,NSBitmapImageRep(cgImage:) 可以避免一些分辨率问题。
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: [:])
}
}