cocoa png core-graphics cgimage

cocoa - ¿Guardar CGImageRef en un archivo png?



core-graphics (3)

Aquí hay un ejemplo de macOS, Swift 3 y 4:

@discardableResult func writeCGImage(_ image: CGImage, to destinationURL: URL) -> Bool { guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else { return false } CGImageDestinationAddImage(destination, image, nil) return CGImageDestinationFinalize(destination) }

en mi aplicación Cocoa, cargo un archivo .jpg desde el disco, lo manipulo. Ahora debe escribirse en el disco como un archivo .png. Como puedes hacer eso?

¡Gracias por tu ayuda!


Usar CGImageDestination y pasar kUTTypePNG es el enfoque correcto. Aquí hay un fragmento rápido:

@import MobileCoreServices; // or `@import CoreServices;` on Mac @import ImageIO; BOOL CGImageWriteToFile(CGImageRef image, NSString *path) { CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL); if (!destination) { NSLog(@"Failed to create CGImageDestination for %@", path); return NO; } CGImageDestinationAddImage(destination, image, nil); if (!CGImageDestinationFinalize(destination)) { NSLog(@"Failed to write image to %@", path); CFRelease(destination); return NO; } CFRelease(destination); return YES; }

Tendrá que agregar CoreServices y CoreServices (o MobileCoreServices en iOS) a su proyecto e incluir los encabezados.

Si tienes iOS y no necesitas una solución que también funcione en Mac, puedes usar un enfoque más simple:

// `image` is a CGImageRef // `path` is a NSString with the path to where you want to save it [UIImagePNGRepresentation([UIImage imageWithCGImage:image]) writeToFile:path atomically:YES];

En mis pruebas, el enfoque de ImageIO fue aproximadamente un 10% más rápido que el enfoque de UIImage en mi iPhone 5s. En el simulador, el enfoque de UIImage fue más rápido. Probablemente valga la pena probar cada uno para su situación particular en el dispositivo si realmente está preocupado con el rendimiento.


Cree un CGImageDestination , pasando kUTTypePNG como el tipo de archivo para crear. Agregue la imagen, luego finalice el destino.