2009-11-19 19 views
8

Chcę utworzyć miniaturę za pomocą CG. Tworzy miniatury.CGImage utworzyć miniaturę obrazu o pożądanym rozmiarze

Tutaj chcę mieć miniaturę o rozmiarze 1024 (ze współczynnikiem kształtu). Czy można uzyskać miniaturę o pożądanym rozmiarze bezpośrednio z CG?

W słowniku opcji mogę przekazać maksymalny rozmiar thumnail może zostać utworzony, ale czy istnieje sposób, aby mieć minimalny rozmiar dla tego samego ..?

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

Odpowiedz

18

Jeśli chcesz miniaturę o rozmiarze 1024 (maksymalny wymiar), powinny być przechodzącą 1024, a nie 2048. Ponadto, jeśli chcesz, aby upewnić się, że miniatur jest tworzony do specyfikacji, to należy z prośbą o kCGImageSourceCreateThumbnailFromImageAlways, a nie kCGImageSourceCreateThumbnailFromImageIfAbsent, ponieważ ta ostatnia może spowodować użycie istniejącej miniatury i może być mniejsza niż oczekiwana.

Tak więc, oto kod, który robi to, co pytasz:

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 3 wersję odpowiedź:

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) 
} 
Powiązane problemy