2009-11-19 20 views
8

Kük resmini CG kullanarak oluşturmak istiyorum. Küçük resimleri oluşturur.CGImage İstenilen boyutta küçücük resim oluştur

Burada minik resmi 1024 (en boy oranıyla) sahip olmak istiyorum. İstenen boyut minik resmini doğrudan CG'den almak mümkün mü?

Seçenekler sözlüğünde, thumnail'ın maksimum boyutunu oluşturabilirim ama aynı boyutta min büyüklüğüne sahip olmanın bir yolu var mı ..? Eğer boyutu 1024 (maksimum boyut) ile bir resmini isterseniz küçük resim senin özelliklerine oluşturulan emin olmak için eğer

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

cevap

18

, size soran, aynı zamanda değil, 1024 2048 olmalıdır geçen edilmelidir kCGImageSourceCreateThumbnailFromImageAlways, kCGImageSourceCreateThumbnailFromImageIfAbsent değil, çünkü mevcut bir küçük resmin kullanılmasına neden olabilir ve istediğinizden daha küçük olabilir. cevap

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 sürümü:

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

Yani, burada kod sormak yapar işte

İlgili konular