Pregunta

Digamos que quiero saber el tamaño de una imagen, de modo que si un usuario intenta cargar una imagen de 10,000x10,000 píxeles en mi aplicación para iPad, puedo presentarle un cuadro de diálogo y no fallar.Si lo hago [UIImage imageNamed:] o [UIImage imageWithContentsOfFile:] eso cargará mi imagen potencialmente grande en la memoria inmediatamente.

Si uso Core Image en su lugar, diga así:

CIImage *ciImage = [CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:imgPath]];

Entonces pregúntale a mi nuevo CIImage por su tamaño:

CGSize imgSize = ciImage.extent.size;

¿Eso cargará la imagen completa en la memoria para decirme esto, o simplemente mirará los metadatos del archivo para descubrir el tamaño de la imagen?

¿Fue útil?

Solución

El imageWithContentsOfURL La función carga la imagen en la memoria, sí.

Afortunadamente Apple implementó CGImageSource Para leer metadatos de imágenes sin cargar los datos de píxeles reales en la memoria en iOS4, puede leer sobre cómo usarlos. en esta publicación de blog (Convenientemente proporciona un ejemplo de código sobre cómo obtener las dimensiones de la imagen).

EDITAR:Ejemplo de código pegado aquí para proteger contra la descomposición del enlace:

#import <ImageIO/ImageIO.h>

NSURL *imageFileURL = [NSURL fileURLWithPath:...];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
if (imageSource == NULL) {
    // Error loading image
    ...
    return;
}

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                     [NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache,nil];
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (CFDictionaryRef)options);
if (imageProperties) {
    NSNumber *width = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
    NSNumber *height = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
    NSLog(@"Image dimensions: %@ x %@ px", width, height);
    CFRelease(imageProperties);
}

La referencia API completa es también disponible aquí.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top