2009-08-24 15 views

Respuesta

13

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

+0

ivanceras: http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/CGImageDestination/ Si quieren una respuesta más específica, debe hacer una pregunta más específica (y debe hacerlo como una pregunta separada). –

+0

Solo una nota. Tenemos que agregar 'ImageIO.framework' para hacer referencia a las funciones, incluso la documentación dice que está en' ApplicationServices/ImageIO'. – Eonil

+1

@Eonil: Depende de la plataforma para la que esté construyendo. Cocoa Touch no tiene marcos de paraguas, por lo que al construir para iOS, es necesario vincular directamente con ImageIO. Al compilar para Mac OS X, se vincula con ApplicationServices y obtiene todo lo que contiene. –

89

Usar CGImageDestination y aprobar kUTTypePNG es el enfoque correcto. He aquí un fragmento rápida:

@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; 
} 

Usted tendrá que añadir ImageIO y CoreServices (o MobileCoreServices en IOS) a su proyecto e incluir las cabeceras.


Si estás en iOS y no necesita una solución que funciona en Mac también se puede utilizar 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 estaba a punto ImageIO 10% más rápido que el enfoque 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.

+0

¿Tiene algún detalle sobre cuál de estos es más eficiente, en términos de tiempo y memoria? Gracias. –

+0

Actualicé mi respuesta con información de rendimiento :) –

16

Aquí es una macOS ambiente, Swift 3 4 & ejemplo:

@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) 
} 
Cuestiones relacionadas