How to save PNG file from NSImage (retina issues)

后端 未结 6 942
情话喂你
情话喂你 2020-11-29 01:37

I\'m doing some operations on images and after I\'m done, I want to save the image as PNG on disk. I\'m doing the following:

+ (void)saveImage:(NSImage *)ima         


        
6条回答
  •  执念已碎
    2020-11-29 02:24

    Just incase anyone stumbles up on this thread. Here is certainly flawed solution that does the job of saving image at 1x size (image.size) regardless of device in swift

    public func writeToFile(path: String, atomically: Bool = true) -> Bool{
    
        let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(self.size.width), pixelsHigh: Int(self.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
        bitmap.size = self.size
    
        NSGraphicsContext.saveGraphicsState()
    
        NSGraphicsContext.setCurrentContext(NSGraphicsContext(bitmapImageRep: bitmap))
        self.drawAtPoint(CGPoint.zero, fromRect: NSRect.zero, operation: NSCompositingOperation.CompositeSourceOver, fraction: 1.0)
        NSGraphicsContext.restoreGraphicsState()
    
        if let imagePGNData = bitmap.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [NSImageCompressionFactor: 1.0]) {
            return imagePGNData.writeToFile((path as NSString).stringByStandardizingPath, atomically: atomically)
        } else {
            return false
        }
    }
    

提交回复
热议问题