Skip to content

Instantly share code, notes, and snippets.

@yauhenidrobau
Created July 26, 2018 14:10
Show Gist options
  • Select an option

  • Save yauhenidrobau/4119628885c4dc7d112d872053ee9618 to your computer and use it in GitHub Desktop.

Select an option

Save yauhenidrobau/4119628885c4dc7d112d872053ee9618 to your computer and use it in GitHub Desktop.
extension UIImage {
private static let defaultThumbSize = CGSize(width: 640, height: 480)
func generatePreview() -> Data? {
guard let imageData = UIImageJPEGRepresentation(self, 0.5) else { return nil }
guard let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil }
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? Dictionary<String, Any> else { return nil }
guard let width = properties[kCGImagePropertyPixelWidth as String] as? Float else { return nil }
guard let height = properties[kCGImagePropertyPixelHeight as String] as? Float else { return nil }
let maxThumbSize = width > height ? UIImage.defaultThumbSize.width : UIImage.defaultThumbSize.height
let options: [NSString: Any] = [
kCGImageSourceThumbnailMaxPixelSize: maxThumbSize,
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true
]
guard let preview = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) else { return nil }
guard let data = UIImageJPEGRepresentation(UIImage(cgImage: preview), 0.5) else { return nil }
return data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment