Created
July 26, 2018 14:10
-
-
Save yauhenidrobau/4119628885c4dc7d112d872053ee9618 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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