2009-11-19 17 views
8

Quiero crear la miniatura usando el CG. Crea las miniaturas.CGImage crear imagen en miniatura con el tamaño deseado

Aquí quiero tener la miniatura con el tamaño 1024 (con relación de aspecto). ¿Es posible obtener la miniatura del tamaño deseado directamente desde el CG?

En el diccionario de opciones puedo pasar el tamaño máximo del thumnail se puede crear, pero ¿hay alguna manera de tener un tamaño mínimo para el mismo ...?

NSURL * url = [NSURL fileURLWithPath:inPath]; 
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL); 
CGImageRef image=nil; 
if (source) 
{ 
    NSDictionary* thumbOpts = [NSDictionary dictionaryWithObjectsAndKeys: 
      (id) kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform, 
      (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent, 
      [NSNumber numberWithInt:2048], kCGImageSourceThumbnailMaxPixelSize, 

      nil]; 

    image = CGImageSourceCreateThumbnailAtIndex(source, 0, (CFDictionaryRef)thumbOpts); 

    NSLog(@"image width = %d %d", CGImageGetWidth(image), CGImageGetHeight(image)); 
    CFRelease(source); 
} 

Respuesta

18

Si desea obtener una miniatura con un tamaño de 1024 (dimensión máxima), que debe estar pasando 1024, no 2048. Además, si usted quiere asegurarse de que la imagen se crea a sus especificaciones, debe estar pidiendo kCGImageSourceCreateThumbnailFromImageAlways, no kCGImageSourceCreateThumbnailFromImageIfAbsent, ya que este último puede hacer que se use una miniatura existente, y podría ser más pequeña de lo que desea.

tanto, aquí está el código que hace lo que pide:

NSURL* url = // whatever; 
NSDictionary* d = [NSDictionary dictionaryWithObjectsAndKeys: 
        (id)kCFBooleanTrue, kCGImageSourceShouldAllowFloat, 
        (id)kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform, 
        (id)kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways, 
        [NSNumber numberWithInt:1024], kCGImageSourceThumbnailMaxPixelSize, 
        nil]; 
CGImageSourceRef src = CGImageSourceCreateWithURL((CFURLRef)url, NULL); 
CGImageRef imref = CGImageSourceCreateThumbnailAtIndex(src, 0, (CFDictionaryRef)d); 
// memory management omitted 
2

Swift versión 3 de la respuesta:

func loadImage(at url: URL, maxDimension max: Int) -> UIImage? { 

    guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) 
     else { 
      return nil 
    } 

    let options = [ 
     kCGImageSourceShouldAllowFloat as String: true as NSNumber, 
     kCGImageSourceCreateThumbnailWithTransform as String: true as NSNumber, 
     kCGImageSourceCreateThumbnailFromImageAlways as String: true as NSNumber, 
     kCGImageSourceThumbnailMaxPixelSize as String: max as NSNumber 
    ] as CFDictionary 

    guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options) 
     else { 
      return nil 
    } 

    return UIImage(cgImage: thumbnail) 
} 
Cuestiones relacionadas