Creating a thumbnail from UIImage using CGImageSourceCreateThumbnailAtIndex

前端 未结 3 528
孤街浪徒
孤街浪徒 2021-02-02 03:48

I want to use the function CGImageSourceCreateThumbnailAtIndex to create a thumbnail from an UIImage. All I have is the UIImage itself. Th

相关标签:
3条回答
  • 2021-02-02 04:28

    Have you try using CGImageSourceCreateWithData and passing image data as CFDataRef like this.

    NSData *imageData = UIImagePNGRepresentation(image);
    CGImageSourceRef src = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    CFDictionaryRef options = (__bridge CFDictionaryRef) @{
                                                         (id) kCGImageSourceCreateThumbnailWithTransform : @YES,
                                                         (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                                         (id) kCGImageSourceThumbnailMaxPixelSize : @(width)
                                                         };
    
    CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
    UIImage *scaled = [UIImage imageWithCGImage:scaledImageRef];
    CGImageRelease(scaledImageRef);
    return scaled;
    

    Note: If you have URL of image then you can create CGImageSourceRef using CGImageSourceCreateWithURL.

    CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef)(imageFileURL), NULL);
    
    0 讨论(0)
  • 2021-02-02 04:41

    Swift 5.1 extension

    based on Ivan's answer

    extension UIImage {
    
      func getThumbnail() -> UIImage? {
    
        guard let imageData = self.pngData() else { return nil }
    
        let options = [
            kCGImageSourceCreateThumbnailWithTransform: true,
            kCGImageSourceCreateThumbnailFromImageAlways: true,
            kCGImageSourceThumbnailMaxPixelSize: 300] as CFDictionary
    
        guard let source = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil }
        guard let imageReference = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else { return nil }
    
        return UIImage(cgImage: imageReference)
    
      }
    }
    
    0 讨论(0)
  • 2021-02-02 04:49

    Swift 4 code

    let imageData = UIImagePNGRepresentation(image)!
    let options = [
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceThumbnailMaxPixelSize: 300] as CFDictionary
    let source = CGImageSourceCreateWithData(imageData, nil)!
    let imageReference = CGImageSourceCreateThumbnailAtIndex(source, 0, options)!
    let thumbnail = UIImage(cgImage: imageReference)
    
    0 讨论(0)
提交回复
热议问题