2009-11-19 25 views
8

我想使用CG創建縮略圖。它創建縮略圖。CGImage創建想要的大小的縮略圖

這裏我想要縮略圖的大小爲1024(帶縱橫比)。是否可以直接從CG中獲得想要的大小縮略圖?

在選項字典我可以通過thumnail的最大尺寸可以創建,但有沒有什麼辦法讓最小尺寸相同..?

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

回答

18

如果你想與大小爲1024(最大尺寸)的縮略圖,您應通過1024,2048不另外,如果你想確保縮略圖創建您的要求,您應要求kCGImageSourceCreateThumbnailFromImageAlways,而不是kCGImageSourceCreateThumbnailFromImageIfAbsent,因爲後者可能會導致使用現有的縮略圖,並且可能比您想要的要小。

所以,這裏的代碼,做什麼你問:

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

斯威夫特3版本的答案:

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